Angular 4:注入 HttpClient 的优势是什么 [英] Angular 4: What is advantage of injecting HttpClient

查看:24
本文介绍了Angular 4:注入 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆