Angular 4:注入 HttpClient 的优势是什么 [英] Angular 4: What is advantage of injecting HttpClient
问题描述
在
Following Angular docs, HttpClient
is injected into the app
component. I saw on another guide that this was a "favorable" without explanation.
@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'];
});
}
}
On this I have some questions:
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?
HttpClient/HttpClientModule introduced in ng 4.3+ are re-implementation of the Http/HttpModule. To mention one example feature, instead of mapping your GET result(s) into JSON and then digging into properties which may or may not exist, you can now cast the returned result into user-defined interface where results/errors are controlled. As an example, and after you update your cli and npm, make a project like the one in the image and see the titles in your browser! See, in your interface, you can pick and choose what you want mapped back.
这篇关于Angular 4:注入 HttpClient 的优势是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!