Binding a class to an interface

前端 未结 2 2059
伪装坚强ぢ
伪装坚强ぢ 2020-12-24 01:55

Using typescript, I can easily bind classes to themselves:

bootstrap(MyAppComponent, [MyClass]);

However, I would like to bind my class to

2条回答
  •  醉梦人生
    2020-12-24 02:35

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

提交回复
热议问题