将配置参数传递给在Angular 2

时间:2017-10-24 13:03:23

标签: angular dependency-injection angular-services

我有一个BaseDataService

export class BaseDataService {
   public cacheKey: string;

   constructor(public cacheService: CacheService) {}

   //some methods and stuff
}

一些扩展BaseDataService的服务:

@Injectable()
export class HeroService extends BaseDataService {
   //some methods and stuff
}

@Injectable()
export class VillainService extends BaseDataService {
   //some methods and stuff
}

我需要为BaseDataService中定义的属性cacheKey设置不​​同的值,我想实现它做这样的事情:

@NgModule({
   providers: [
      {provide: HeroService, useClass: HeroService, deps:[CacheService, 'cacheKeyForHeroes']},
      {provide: VillainService, useClass: VillainService, deps:[CacheService, 'cacheKeyForVillains']},
      CacheService
   ],
   bootstrap: [AppComponent],
})
export class AppModule {}

显然,这是失败的,因为第二个依赖项不是Injectable,但我想知道如何将静态配置传递给我的服务。

感谢所有人!

2 个答案:

答案 0 :(得分:0)

@NgModule({
   providers: [
      {provide: HeroService, useFactory: () => new HeroService(new CacheService('cacheKeyForHeroes'))},
      {provide: VillainService, useFactory: () => new VillainService(new CacheService('cacheKeyForVillains'))},
   ],
   bootstrap: [AppComponent],
})
export class AppModule {}

@Injectable()
export class HeroService extends BaseDataService {
   constructor(HeroCacheService cache) { super(cache); }
}
@Injectable()
export class VillainService extends BaseDataService {
   constructor(VillainCacheService cache) { super(cache); }
}
@Injectable()
export class HeroCacheService extends CacheService {
  constructor(@Inject('heroCacheKey') key:String) { super(key); }
}
@Injectable()
export class VillainCacheService extends CacheService {
  constructor(@Inject('villainCacheKey') key:String) { super(key); }
}

@NgModule({
   providers: [
      HeroService,
      VillainService,
      HeroCacheService,
      VillainCacheService,
      {provide: 'heroCacheKey', useValue: 'cacheKeyForHeroes'},
      {provide: 'villainCacheKey', useValue: 'cacheKeyForVillains'},
   ],
   bootstrap: [AppComponent],
})
export class AppModule {}

答案 1 :(得分:0)

找到解决方案。您不能将简单字符串作为服务的依赖项传递。你必须这样做:

@NgModule({
   providers: [
      {provide: 'heroCacheKey', useValue: 'heroCacheKeyValue'},
      {provide: HeroService, useClass: HeroService, deps:[CacheService, 'heroCacheKey']},
      {provide: 'villainCacheKey', useValue: 'villainCacheKeyValue'},
      {provide: VillainService, useClass: VillainService, deps:[CacheService, 'villainCacheKey']},
      CacheService
   ],
   bootstrap: [AppComponent],
})
export class AppModule {}

并像这样修改BaseDataService:

export class BaseDataService {

  constructor(public cacheService: CacheService, public cacheKey: string) {}

  //some methods and stuff
}