@NgModule, @Injectable @Componenet:依赖注入和代码复用

@NgModule, @Injectable @Componenet: Dependency injection and code reuse

我需要将服务注入组件。所有这些都在 app.module 中指定,如下例所示。

但是我目前的理解是 Angular 依赖注入支持使用 类 编程而不是接口。

例如:我有两个服务。 DogService 和 CatService 都实现了 AnimalServiceInferface。

export interface AnimalServiceInferface {
    makeSound(): String;
}

@Injectable()
export class DogService implements AnimalServiceInferface {
    makeSound(): String {
        return "Woof";
    }
}

@Injectable()
export class CatService implements AnimalServiceInferface {
    makeSound(): String {
        return "Woof";
    }
}

然后我像这样连接我的@NgModule

@NgModule({
    imports: [
        APP_ROUTES,
        BrowserModule
    ],
    declarations: [
        AnimalComponent
    ],
    providers: [
        CatService,
        DogService
    ],
    bootstrap: [
        AppComponent
    ]
})

然后,在我的组件中,我需要使用这两种服务中的任何一种。

@component()
export class AnimalComponent implements OnInit {

    animalSound: string;

    constructor(animalService: AnimalServiceInferface) {
    }

    onInit() {
        this.animalSound = animalService.makeSound();
    }

}

我如何连接它以便我的应用程序可以同时使用 AnimalServiceInferface 实现,但使用的实现取决于具体情况。例如,这可以根据特定路线或不同的组件配置来确定。

非常感谢

JT

您可以使用字符串或 OpaqueToken 作为键

providers: [
    { provide: 'AnimalService': useClass: CatService},
    // { provide: 'AnimalService': useClass: DogService}
],
constructor(@Inject('AnimalService') animalService: AnimalServiceInferface) {

是否注入 CatServiceDogService 取决于您提供它们的位置。如果路由组件注册了一个提供者,那么它的后代将获得这个实例。如果没有,则 DI 将向上查找,直到找到具有匹配键的提供者和 return 它找到的第一个提供者的实例。