我正在尝试使用服务的策略模式,但是我尝试用作策略上下文的模块似乎只坚持两者之一。这是示例代码:
动物模块.ts
@Module({})
export class AnimalModule {
static register(strategy): DynamicModule {
return {
module: AnimalModule,
providers: [{ provide: 'STRATEGY', useValue: strategy }, AnimalService],
imports: [],
exports: [AnimalService]
};
}
}
Run Code Online (Sandbox Code Playgroud)
动物服务.ts
@Injectable()
export class AnimalService {
constructor (@Inject('STRATEGY') private strategy) {
this.strategy = strategy
}
public makeSound() {
return this.strategy.makeSound()
}
}
Run Code Online (Sandbox Code Playgroud)
猫模块.ts
@Module({
imports: [
AnimalModule.register(catStrategy),
],
controllers: [CatController],
providers: [CatService],
})
export class CatModule {}
Run Code Online (Sandbox Code Playgroud)
猫服务.ts
@Injectable()
export class CatService {
constructor(
private readonly animalService: AnimalService,
) {} …Run Code Online (Sandbox Code Playgroud)