After reviewing the Angular Official documents and various blogs, I noticed that there are two different syntaxes for Dependency Injection (DI) when used within the constructor. Sometimes this
is utilized, while other times it is not. This leads to the question - which approach is correct?
It is common knowledge that we use this
in any other method of a class, but why is it omitted in the constructor? Is it simply due to the usage of the private
and public
identifiers making a difference in the utilization of this
?
import { Component } from '@angular/core';
class NameService {
getName () {
return "Angular";
}
}
@Component({
selector: 'my-app',
template: '<h1>Favourite framework: {{ name }}</h1>'
})
class AppComponent {
name: string;
constructor(nameService: NameService) {
this.name = nameService.getName(); // do not use this
}
otherMethod() {
this.nameService.getName(); // use this
}
}
In some instances, individuals include this
within the constructor. An example can be found here.
constructor(@Optional() private logger: Logger) {
if (this.logger) {
this.logger.log(some_message); // using this
}
}
So when exactly should we use this
and when shouldn't we? Perhaps the presence of the @Optional
decorator in the latter example triggers the use of this
?