绑定类的接口 [英] Binding a class to an interface

查看:176
本文介绍了绑定类的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用打字稿,我可以很容易地绑定类自己:

 引导(MyAppComponent,[MyClass的]);

不过,我想我的类绑定到一个接口,这样的一样:

 自举(MyAppComponent,[???]);

这样我可以如下注入它:

 类MyAppComponent {
    构造函数(my_class:IMyClass){
    }
};

这是可能的Angular2?如果是的话,我怎么能有指定绑定?


解决方案

要使它短问题是,当打字稿编译接口消失。所以,你不得不使用@Inject一个字符串。

或者还有另一种选择,如果你检查维克多的最后一篇文章Savkin 你可以在评论中发现这个:


  

一些背景。在打字稿,接口结构和在运行时不会保留。所以,你必须使用ILoginService如下:


 构造(@注入(ILoginService)S:ILoginService)。


  

您不必使用一个字符串 - 任何对象都可以在那里进行传递。实际上,我们提供称为OpaqueToken一个目的,可用于该目的。


 接口ILoginService {登录(凭证);}
常量ILoginService =新OpaqueToken(login服务);


  

可以使用这样的:


 构造(@注入(ILoginService)S:ILoginService)。

Using typescript, I can easily bind classes to themselves:

bootstrap(MyAppComponent, [MyClass]);

However, I would like to bind my class to an interface, like such:

boostrap(MyAppComponent, [???]);

such that I can inject it as follows:

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

Is this possible in Angular2? If yes, how to I have to specify the binding?

解决方案

To make it short the problem is that Interfaces disappear when typescript is compiled. So you'd have to use @Inject with a string.

Or there's another option, if you check the last article of Victor Savkin you can find this in the comments :

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).

这篇关于绑定类的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆