【问题标题】:Angular service calls a service by same interface/abstract class => cyclic dependencyAngular 服务通过相同的接口/抽象类调用服务 => 循环依赖
【发布时间】:2021-02-02 04:58:54
【问题描述】:

我想调用一个调用服务的服务。两者都被注入并使用相同的接口/抽象类。

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

不重复自己如何做到这一点?

【问题讨论】:

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


    【解决方案1】:

    将 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

    2020 年 10 月 21 日更新

    我想调用一个调用服务的服务。两者都被注入并使用相同的接口/抽象类。

    这意味着

    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

    【讨论】:

    • 非常感谢!不幸的是,现在AService 被省略了。添加return "A says:" + this.service.getTitle(); 不显示。
    • 在您的初始帖子中没有提及您的 sn-p
    • 是的,但是我写了“我想调用一个调用服务的服务”。我提到这个 sn-p 是为了表明你的例子做了一些不同的事情,以防有任何疑问。
    • 在 StackBlitz 示例中,我已将 console.log 调整为 console.log("A says: " + this.service.getTitle());,字符串按预期打印出来。
    • 谢谢。 “我想调用一个调用服务的服务。两者都被注入并使用相同的接口/抽象类。”你的例子真的做到了吗?我不这么认为。例如,在 Java 等其他语言中也是可能的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 2020-07-31
    • 2018-11-18
    • 2019-03-24
    • 1970-01-01
    相关资源
    最近更新 更多