我使用 Angular 8。
这个问题只针对 Angular DI 专家。
起初,我制作了一个 Angular 库,它将在许多项目中重用。
在这个库中,我做了一个抽象服务,必须在使用它的项目中定义。
我在名为 BridgeService 的库中定义了一个抽象类
在我的主项目中,我创建了实现它的 BridgeService:(在接下来的几行中,我将向您展示抽象的 BridgeService)
MainProject > BridgeService :
import { BridgeService as AbstractBridgeService } from 'myLibrary';
@Injectable()
export class BridgeService implements AbstractBridgeService {
hello(){
alert('hello Word');
}
}
主项目 > 用户模块:
import { UsersModule as LibraryUsersModule } from 'myLibrary';
@NgModule({
imports: [
CommonModule,
LibraryUsersModule,
],
//...
providers: [
BridgeService
// some try:
//{ provide: BridgeService, useClass: BridgeService }
],
})
export class UsersModule {
constructor(private bridgeService: BridgeService){
this.bridgeService.hello();
}
}
现在我们必须查看有关库的文件:
图书馆 > bridge.service.ts:
export abstract class BridgeService {
abstract hello(): void;
}
此 BridgeService 必须在 UsersModule 中定义
图书馆 > 用户模块:
@NgModule({
//...
providers: [
// My Try:
{ provide: BridgeService, useValue: BridgeService}
],
})
export class UsersModule {
# my goal is that I can uncomment this piece of code:
//constructor(private bridgeService: BridgeService){
// this.bridgeService.hello();
//}
}
我希望你只触摸这段代码中的两行:
1) 在库的 UsersModule 提供程序数组中:我想声明为通用抽象的 BridgeService 行。
2) 在项目的 UsersModule 提供者数组中:我要定义的 BridgeService 行来代替 Library UserModule 中的抽象。