使用typescript,我可以轻松地将类绑定到自己:
bootstrap(MyAppComponent,[MyClass]);
但是,我想将我的类绑定到一个接口,如下所示:
boostrap(MyAppComponent,[???]);
这样我可以按如下方式注入:
class MyAppComponent { constructor(my_class : IMyClass){ } };
这在Angular2中可能吗?如果是,我该如何指定绑定?
简而言之,问题是编译typescript时接口消失了。所以你必须使用带有字符串的@Inject。
原文链接:https://www.f2er.com/angularjs/143904.html或者还有另一种选择,如果你检查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).