Angular 4:注入HttpClient的好处是什么 [英] Angular 4: What is advantage of injecting HttpClient
问题描述
在角度文档之后,将HttpClient
注入到app
组件中.我在另一本指南上看到这是有利的",没有解释.
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'];
});
}
}
对此,我有一些疑问:
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?
ng 4.3+中引入的
推荐答案
HttpClient/HttpClientModule是Http/HttpModule的重新实现.提到一个示例功能,您现在可以将返回的结果转换为用户定义的界面,以控制结果/错误,而不是将GET结果映射到JSON,然后再挖掘可能存在或可能不存在的属性.例如,更新cli和npm后,创建一个与图片中的项目类似的项目,然后在浏览器中查看标题!看,在您的界面中,您可以选择要映射回的内容.
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屋!