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

dependency-injection – 将类绑定到接口

发布时间:2020-12-17 08:01:58 所属栏目:安全 来源:网络整理
导读:使用typescript,我可以轻松地将类绑定到自己: bootstrap(MyAppComponent,[MyClass]); 但是,我想将我的类绑定到一个接口,如下所示: boostrap(MyAppComponent,[???]); 这样我可以按如下方式注入: class MyAppComponent { constructor(my_class : IMyClas
使用typescript,我可以轻松地将类绑定到自己:
bootstrap(MyAppComponent,[MyClass]);

但是,我想将我的类绑定到一个接口,如下所示:

boostrap(MyAppComponent,[???]);

这样我可以按如下方式注入:

class MyAppComponent {
    constructor(my_class : IMyClass){
    }
};

这在Angular2中可能吗?如果是,我该如何指定绑定?

简而言之,问题是编译typescript时接口消失了。所以你必须使用带有字符串的@Inject。

或者还有另一种选择,如果你检查the last article of Victor Savkin 你可以在评论中找到它:

Some background. In TypeScript,interfaces are structural and are not retained at runtime. So you have to use ILoginService as follows:

constructor(@Inject("ILoginService") s:ILoginService).

You don’t have to use a string – any object can be passed in there. We actually provide an object called OpaqueToken that can be used for this purpose.

interface ILoginService { login(credentials);}
const ILoginService = new OpaqueToken("LoginService");

can be used like this:

constructor(@Inject(ILoginService) s:ILoginService).

(编辑:李大同)

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

    推荐文章
      热点阅读