【问题标题】:How can I use service inside other service without providers array and providedIn?如何在没有提供者数组和提供的服务的情况下在其他服务中使用服务?
【发布时间】:2021-11-29 14:04:57
【问题描述】:

我需要在 Service2 中使用 Service1,但我不想将 Service1 用作 Singleton 并通过模块中的 providers 数组和在服务定义中提供的来定义它。

我想在组件级别使用它,然后我们在组件装饰器中使用提供者数组。

有可能吗?

import { Injectable } from '@angular/core';

@Injectable()
export class Service1 {
  doSmth(){
  }
}


@Injectable()
export class Service2 {
  doSmth(){
  }
}

和类似的情况,那么我需要在 Ngrx Effects 中使用“not-singleton”服务。我该怎么办?

【问题讨论】:

    标签: angular


    【解决方案1】:

    必须在某处提供 Injectable。也许我不完全理解这一点,但也许你可以删除 Injectable 装饰器并只使用类构造函数来获取类的实例,因为你不想要单例实例?

    @Injectable()
    export class Service2 {
      service1 = new Service1();
    }
    

    【讨论】:

    • 也许吧。如何使用Service1的构造函数,那么它需要例如http:HttpClient作为参数?
    • 在Service2中注入,然后传入Service1的构造函数中
    猜你喜欢
    • 1970-01-01
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 2019-05-29
    相关资源
    最近更新 更多