Federico P Federico P - 2 months ago 10
TypeScript Question

When to assign services to 'this' in angular2 components or services?

There are two ways that I see people using services in their components and or other services. A common use case is the

Http
service. Both cases import it:

import { Http } from '@angular/http';


Case 1:

constructor ( private http: Http ) {
this.http = http;
}


Case 2:

constructor ( private http: Http ) { }


Both cases result in the
Http
service being available at
this.http
.

Is there an advantage to using case 1 over case 2? Does it have to do with multiple instantiations?

Answer

There's no need for this.http = http because

constructor ( private http: Http ) { }

transpiles to this.http = http and results in doing this twice.

It's either that, or

constructor (@Inject(Http) http) {
  this.http = http;
}

if the compatibility with ES.next and Babel is in priority.