Angular2我可以同时使用@optional或?表示构造函数中的可选参数.我尝试了两者,它看起来很相似.
他们之间有什么区别?
他们之间有什么区别?
解决方法
@Optional将依赖项标记为可选,因此即使未定义依赖项的服务提供程序,注入器也不会引发异常.
@H_404_12@
@H_404_12@?是一个Typescript符号,它将函数参数标记为可选,因此它的目的与@Optional不同.
@H_404_12@如果使用?代替@Optional,Injector仍将尝试解决依赖关系,如果不能,则会引发异常.
@H_404_12@
https://embed.plnkr.co/jEZISqAksYWdaaBTFGd0/
class Engine {} @Directive({ selector: 'child-directive' }) class ChildDirective { constructor(@Optional() @Host() os:OtherService,@Optional() @Host() hs:HostService,public engine?: Engine){ console.log("os is null",os); console.log("hs is NOT null",hs); console.log(this.engine); } }@H_404_12@如果未定义Engine服务,这将引发异常 @H_404_12@
EXCEPTION: No provider for Engine! (ChildDirective -> Engine)@H_404_12@这是plunk链接.
https://embed.plnkr.co/jEZISqAksYWdaaBTFGd0/