以下Angular docs,HttpClient
被注入app
組件。我在另一位導遊看到,這是一個「有利的」,沒有解釋。角4:注入HttpClient的優勢是什麼
@Component(...)
export class MyComponent implements OnInit {
results: string[];
// Inject HttpClient into your component or service.
constructor(private http: HttpClient) {}
ngOnInit(): void {
// Make the HTTP request:
this.http.get('/api/items').subscribe(data => {
// Read the result field from the JSON response.
this.results = data['results'];
});
}
}
在此我有一些問題:
1) Where/How is the HttpClient actually instantiated? Does `ng serve` handle this?
2) How could I inject a different instance if I needed to?
'我上的另一個導向看到,這是一個「有利的」,而不explanation' <=請提供源。也許你誤解了,這對'http'有利,因爲'http'將被棄用。 – Igor
關於2,請參閱https://stackoverflow.com/questions/38213995/angular2-di-initializing-multiple-different-instances-in-the-same-constructor。由於它的設計方式,你將很難用HttpClient做這件事。通常使用一個HttpClient實例。 – estus
關於#2,請參見[依賴注入 - 何時使用NgModule與應用程序組件](https://angular.io/guide/dependency-injection#when-to-use-ng- module-versus-an-application-component )。您可以在組件中指定提供程序,併爲該組件提供新的實例,並且它是子組件。 –