什么时候将服务分配给 angular2 组件或服务中的 'this'?
When to assign services to 'this' in angular2 components or services?
我看到人们通过两种方式在他们的组件和/或其他服务中使用服务。一个常见的用例是 Http
服务。两种情况都导入它:
import { Http } from '@angular/http';
案例 1:
constructor ( private http: Http ) {
this.http = http;
}
案例 2:
constructor ( private http: Http ) { }
这两种情况都会导致 Http
服务在 this.http
可用。
使用案例 1 比使用案例 2 有优势吗?它与多个实例化有关吗?
不需要this.http = http
因为
constructor ( private http: Http ) { }
转译为 this.http = http
并产生 doing this twice。
要么是,要么
constructor (@Inject(Http) http) {
this.http = http;
}
如果与 ES.next 和 Babel 的兼容性优先。
我看到人们通过两种方式在他们的组件和/或其他服务中使用服务。一个常见的用例是 Http
服务。两种情况都导入它:
import { Http } from '@angular/http';
案例 1:
constructor ( private http: Http ) {
this.http = http;
}
案例 2:
constructor ( private http: Http ) { }
这两种情况都会导致 Http
服务在 this.http
可用。
使用案例 1 比使用案例 2 有优势吗?它与多个实例化有关吗?
不需要this.http = http
因为
constructor ( private http: Http ) { }
转译为 this.http = http
并产生 doing this twice。
要么是,要么
constructor (@Inject(Http) http) {
this.http = http;
}
如果与 ES.next 和 Babel 的兼容性优先。