微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用TypeScript,Angular 2和SystemJS进行基于接口的编程

我目前正在尝试清理一些代码,以便针对接口而不是针对实现进行编程,但无法弄清楚如何实现.

更具体地说,我正在使用:
* TypeScript 1.5.0 beta – >转换为ES5 / commonjs
* 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?

Any practical ideas how I can use interface based programming w/ TypeScript & Angular 2

接口在运行时被擦除.事实上,装饰器也不支持接口.因此,最好使用在运行时存在的东西(即实现).

原文地址:https://www.jb51.cc/angularjs/142257.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐