Federico P Federico P - 1 year ago 71
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

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
service being available at

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download