typescript 带可选参数的 DI 构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36446602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DI constructor with optional parameters
提问by KenavR
My constructor has optional parameters and they seem to mess with the predominant way of doing DI.
我的构造函数有可选参数,它们似乎与执行 DI 的主要方式相混淆。
constructor(public name:string, public age?:number, private _service:Service);
Typescript understandably doesn't like that I put a non optional parameter behind an optional one, furthermore the service doesn't get injected when the optional parameter isn't set. How do I solve that? I can't put it somewhere else in the constructor since I would be expected setting the service manually.
可以理解,打字稿不喜欢我将非可选参数放在可选参数后面,而且当可选参数未设置时,服务不会被注入。我该如何解决?我不能把它放在构造函数的其他地方,因为我需要手动设置服务。
Is there something like field injection?
有没有像场注入之类的东西?
@Inject() private _service:Service;
constructor(public name:string, public age?:number);
Should I replace the optional parameters with default values? Any other suggestions?
我应该用默认值替换可选参数吗?还有其他建议吗?
EDIT:As discussed below, I tried to inject a service into an object that isn't created by Angular's DI. This doesn't work. Since I can't create this class (model) using DI I now pass the service manually from the class that instantiates this objects.
编辑:如下所述,我尝试将服务注入到不是由 Angular 的 DI 创建的对象中。这不起作用。由于我无法使用 DI 创建此类(模型),因此我现在从实例化此对象的类手动传递服务。
回答by Günter Z?chbauer
Just add the @Optional()
decorator before the constructor parameter that should only be injected if there was a provider registered.
只需@Optional()
在构造函数参数之前添加装饰器,只有在提供者注册时才应该注入。
constructor(public name:string, @Optional() public age:number)
回答by Cosmin Popescu
If I understand correctly what you are trying to do, you need a service factory. See here: https://angular.io/docs/ts/latest/guide/dependency-injection.html#factory-provider
如果我正确理解您要做什么,您需要一个服务工厂。请参阅此处:https: //angular.io/docs/ts/latest/guide/dependency-injection.html#factory-provider
Basically,
基本上,
class MyClass {
constructor(public name:string, private _service:Service, public age?:number){}
}
And then
接着
let myFactory = (_service: Service) => {
return isAgeOk ? new MyClass(name, _service, age) : new MyClass(name, _service);
};
And then you should provide your service like this:
然后你应该像这样提供你的服务:
providers: [{ provide: MyClass, useFactory: MyFactory, deps: [Service]}]