Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular constructor parameters @optional vs question mark usage

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?

like image 509
Janier Avatar asked Sep 26 '17 17:09

Janier


1 Answers

@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.

like image 89
songxunzhao Avatar answered Sep 28 '22 01:09

songxunzhao