如何在providers中的useFactory中使用单例服务/类:app.module中的[]

时间:2019-05-13 07:14:43

标签: angular typescript

我有父抽象服务

    @Injectable()
    export abstract class parent {}

和两个子服务

    @Injectable()
    export class dataService extends parent {}

    @Injectable()
    export class mockService extends parent {}

现在我想在app.module中基于一些常量变量(即productionStatus)使用useFactory,这意味着如果状态已连接,则使用“数据服务”,否则使用“模拟服务”

这是我目前的工作方式

core.module:

@NgModule({
  providers: [
    {
      provide: PayoutService,
      useFactory:()=> new FactoryConfigService().getPayoutServiceInstance()
    },
    {
      provide: OrderService,
      useFactory:()=> new FactoryConfigService().getOrderServiceInstance()
    }
  ]
})

FactoryConfigService:

export class FactoryConfigService {
  public productionStatus: Connection.Status = Connection.Status.disconnected;

  constructor() { }

  getOrderServiceInstance() {
    if (this.productionStatus == Connection.Status.connected) {
      return new OrderDataService();
    } else {
      return new OrderMockService();
    }
  }
  getPayoutServiceInstance() {
    if (this.productionStatus == Connection.Status.connected) {
      return new PayoutDataService();
    } else {
      return new PayoutMockService();
    }
  }

}

现在我的问题是如何在providers []中使用FactoryConfigService,而不使用“ new”并且作为singleton / injectable

0 个答案:

没有答案