Is it possible to inject interface with angular2?

后端 未结 5 1534
不思量自难忘°
不思量自难忘° 2020-12-02 14:06

i wonder if there is a proper way to inject interfaces in Angular2? (cf. below)

I think this is related with the missing @Injectable() decorator on the interface, bu

5条回答
  •  情书的邮戳
    2020-12-02 14:39

    Use OpaqueToken, interfaces are not supported by DI, beacause Javascript itself haven't interfaces. One way to do this in Angular 2 is by using OpaqueToken. https://angular.io/docs/ts/latest/guide/dependency-injection.html

    import { OpaqueToken } from '@angular/core';
    
    export let APP_CONFIG = new OpaqueToken('app.config');
    
    providers: [{ provide: APP_CONFIG, useValue: HERO_DI_CONFIG }]
    
    constructor(@Inject(APP_CONFIG) config: AppConfig) {
      this.title = config.title;
    }
    

    I hope this can help.

提交回复
热议问题