2016-09-24 74 views
1

有兩種方法可以看到人們在其組件和/或其他服務中使用服務。一個常見的用例是Http服務。這兩種情況下,將其導入:何時在angular2組件或服務中爲「this」分配服務?

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

案例1:

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

案例2:

constructor (private http: Http) { } 

這兩種情況導致Http服務在this.http可用。

對案例2使用案例1有利嗎?它是否與多個實例有關?

回答

1

沒有必要爲this.http = http因爲

constructor (private http: Http) { } 

transpiles到this.http = http並導致doing this twice

它要麼,或

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

如果與ES.next和巴貝爾的兼容性是當務之急。

+0

有趣...所以它不會破壞任何東西,它只是多餘的。當我們不使用'private'關鍵字時,它看起來只對'this.x = x'有用。 [Example playground](http://www.typescriptlang.org/play/#src=class%20Foo%20%7B%0D%0A%20%20%20%20%20constructor(http%3A%20Http)%20%7B %0D 0A%%20%20%20%20%20%20this.http%20%3D%20http%3B%0D 0A%%20%20%20%20%7D%0D 0A%%7D)。謝謝! –

+0

這是正確的。構造函數中的可見性語法正是爲了使「構造函數」函數的主體完整無損(大多數情況下它只是在A2注入中的{}}。 – estus