Angular2 i can use both @optional or ? to denote the optional parameters in a constructor.I tried both and it looks similar. What is the difference between them?
@Optional
marks the dependency as optional, thus injector will not raise an exception even if service provider for the dependency is not defined.
?
is a Typescript symbol which marks the function parameter as optional, so it's purpose is different from @Optional
.
If you use ?
in place of @Optional
the Injector will still try to resolve dependency and if it can't it will raise an exception.
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);
}
}
This will raise exception if Engine service wasn't defined
EXCEPTION: No provider for Engine! (ChildDirective -> Engine)
Here is plunkr demo code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With