带可选参数的DI构造函数 [英] DI constructor with optional parameters

查看:144
本文介绍了带可选参数的DI构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的构造函数具有可选参数,它们似乎与执行DI的主要方式搞混了.

My constructor has optional parameters and they seem to mess with the predominant way of doing DI.

constructor(public name:string, public age?:number, private _service:Service);

可以理解,

Typescript不喜欢我在一个可选参数后面放置一个非可选参数,此外,当未设置可选参数时,不会注入服务.我该如何解决?我不能将其放置在构造函数中的其他位置,因为会期望手动设置服务.

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?

如下所述,我试图将服务注入到不是由Angular的DI创建的对象中.这行不通.由于无法使用DI创建此类(模型),因此我现在从实例化此对象的类中手动传递服务.

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.

推荐答案

只需添加 @Optional() 在构造函数参数之前的装饰器,只有在已注册提供者的情况下,才应插入.

Just add the @Optional() decorator before the constructor parameter that should only be injected if there was a provider registered.

constructor(public name:string, @Optional() public age:number)

这篇关于带可选参数的DI构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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