Angular服务通过相同的接口/抽象类调用服务=>循环依赖

时间:2020-10-19 12:03:18

标签: angular typescript dependency-injection interface abstract-class

我想呼叫服务,而该服务称为服务。两者都被注入并且使用相同的接口/抽象类。

export abstract class Service {
  abstract getTitle(): string;
}

@Injectable({
  providedIn: "root"
})
export class BService extends Service {
  getTitle() {
    return "from B";
  }
}

@Injectable({
  providedIn: "root"
})
export class AService extends Service {
  constructor(private service: Service) {
    super()
  }
  getTitle() {
    return this.service.getTitle();
  }
}
@NgModule({
  providers: [{ provide: Service, useClass: BService }]
})
export class AModule {}
@NgModule({
  imports: [BrowserModule, FormsModule, AModule],
  declarations: [AppComponent, HelloComponent],
  bootstrap: [AppComponent],
  providers: [{ provide: Service, useClass: AService }]
})
export class AppModule {}
export class HelloComponent {
  title: string;
  constructor(service: Service) {
    this.title = service.getTitle();
  }

我得到:

Provider parse errors:
Cannot instantiate cyclic dependency! Service ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1

https://stackblitz.com/edit/angular-tqoena

如何在不重复自己的情况下实现?

1 个答案:

答案 0 :(得分:0)

将AppModule.ts更改为以下

@NgModule({
  imports: [BrowserModule, FormsModule, AModule],
  declarations: [AppComponent, HelloComponent],
  bootstrap: [AppComponent],
  providers: [AService] // <-- Just provide the service
})
export class AppModule {}

AService也不需要扩展抽象服务

@Injectable({
  providedIn: "root"
})
export class AService {
  constructor(private service: Service) {
  }
  getTitle() {
    return this.service.getTitle();
  }
}

请参阅工作示例here

更新21.2020年10月

我想呼叫服务,而该服务称为服务。两者都被注入并且使用相同的接口/抽象类。

什么意思

ServiceA extends Service
ServiceB extends Service
ServiceB is being injected into ServiceA
ServiceA will be called from Component
(ServiceB will also be called from Component)

以上方案已实现here