使用依赖注入将参数传递给服务的构造函数? [英] Passing parameters to constructor of a service using Dependency Injection?

查看:365
本文介绍了使用依赖注入将参数传递给服务的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有自定义服务类:

@Injectable()

export class CustomService {
  constructor(num: number) {
  }
}

此类被注入组件的构造函数中,如下所示:

This class is injected in constructor of component like this:

constructor(private cs: CustomService) {
}

但是如何将参数num传递给上述构造函数中的服务? 像这样的东西:

But how to pass parameter num to service in constructor described above? Something like that:

constructor(private cs: CustomService(1)) {
}

作为解决方案,我可以使用Fabric模式,但是只有一种方法吗?

I know as solution I can use Fabric pattern, but is there only one way to do that?

推荐答案

如果CustomService实例不应该是注入器单例,则为:

If CustomService instances should not be injector singletons, it is:

providers: [{ provide: CustomService, useValue: CustomService }]

...

private cs;

constructor(@Inject(CustomService) private CustomService: typeof CustomService) {
  this.cs = new CustomService(1);
}

如果应该记住CustomService来返回各个参数的单例,则应通过其他缓存服务来检索实例:

If CustomService is supposed be memoized to return singletons for respective parameter, instances should be retrieved through additional cache service:

class CustomServiceStorage {
  private storage = new Map();

  constructor(@Inject(CustomService) private CustomService: typeof CustomService) {}
  get(num) {
    if (!this.storage.has(num))
      this.storage.set(num, new this.CustomService(num));

    return this.storage.get(num);
  }
}

这篇关于使用依赖注入将参数传递给服务的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆