加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:31:23 所属栏目:安全 来源:网络整理
导读:我目前正在尝试清理一些代码,以便针对接口而不是针对实现进行编程,但无法弄清楚如何实现. 更具体地说,我正在使用: * TypeScript 1.5.0 beta – 转换为ES5 / commonjs * SystemJS加载模块 我目前尝试使用外部模块如下: posts.service.ts文件: ///reference
我目前正在尝试清理一些代码,以便针对接口而不是针对实现进行编程,但无法弄清楚如何实现.

更具体地说,我正在使用:
* 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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读