带有抽象类令牌的角度DI

时间:2017-10-03 20:07:02

标签: angular typescript dependency-injection

angular文档显示了如何不将接口用作注入令牌: https://angular.io/guide/dependency-injection#typescript-interfaces-arent-valid-tokens

export interface AppConfig {
  apiEndpoint: string;
  title: string;
}

export const HERO_DI_CONFIG: AppConfig = {
  apiEndpoint: 'api.heroes.com',
  title: 'Dependency Injection'
};

export class MyComponent {
  // FAIL! Can't inject using the interface as the parameter type
  constructor(private config: AppConfig) { }
}

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
    MyComponent
  ],
  providers: [
    {
      // FAIL! Can't use interface as provider token
      provide: AppConfig,
      useValue: HERO_DI_CONFIG
    }
  ]
})
export class MyModule { }

使用抽象类作为注入令牌是否有任何问题:

export abstract class AppConfig {
  public abstract apiEndpoint: string;
  public abstract title: string;
}

export const HERO_DI_CONFIG: AppConfig = {
  apiEndpoint: 'api.heroes.com',
  title: 'Dependency Injection'
};

export class MyComponent {
  // should work
  constructor(private config: AppConfig) { }
}

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
    MyComponent
  ],
  providers: [
    {
      // class exists at runtime
      provide: AppConfig,
      useValue: HERO_DI_CONFIG
    }
  ]
})
export class MyModule { }

或者是利用打字稿吗?

编辑:我知道文档使用了InjectionToken但是使用抽象类作为标记有什么问题?它比constructor(@Inject(APP_CONFIG) config: AppConfig)更安全,你可以撒谎并放constructor(@Inject(APP_CONFIG) config: string)

0 个答案:

没有答案