使用TypeScript,Angular 2和SystemJS进行基于接口的编程
|
我目前正在尝试清理一些代码,以便针对接口而不是针对实现进行编程,但无法弄清楚如何实现.
更具体地说,我正在使用: 我目前尝试使用外部模块如下: posts.service.ts文件: ///<reference path="../../../typings/tsd.d.ts" />
///<reference path="../../../typings/typescriptApp.d.ts" />
...
export interface PostsService{ // 1
fetchPosts(): Rx.Observable<any>;
}
export var PostsService:PostsServiceImpl; // 2
...
export class PostsServiceImpl implements PostsService { // 3
...
constructor(){
console.log('Loading the Posts service');
}
...
fetchPosts(): Rx.Observable<any>{
...
}
并在posts.ts中导入该模块: ///<reference path="../../../typings/tsd.d.ts" />
///<reference path="../../../typings/typescriptApp.d.ts" />
import {PostsService,PostsServiceImpl} from 'components/posts/posts.service';
@Component({
selector: 'posts',viewInjector: [
//PostsServiceImpl
//PostsService
bind(PostsService).toClass(PostsServiceImpl)
]
})
...
export class Posts {
private postsServices: PostsService;
constructor(postsService: PostsService) {
console.log('Loading the Posts component');
this.postsServices = postsService;
...
}
...
}
上面的代码编译正确,但基本上我的问题归结为Angular不会在Posts组件中注入PostsServiceImpl的实例. 当然这只是因为我没有找到正确的方式来声明/导出/导入所有内容 没有导出接口PostsService …,我得到TS编译错误,因为我在posts控制器中使用它. 没有export var PostsService:PostsServiceImpl;我在@View装饰器的viewInjector中得到TS编译错误 在生成的js代码中我只找到exports.PostsService;由于export var而添加的…我知道接口在运行时消失了. 所以我有点迷失了.任何实用的想法如何使用基于接口的编程w / TypeScript&角2?
接口在运行时被擦除.事实上,装饰器也不支持接口.因此,最好使用在运行时存在的东西(即实现). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
