【发布时间】:2017-10-19 18:58:43
【问题描述】:
在Angular docs 之后,HttpClient 被注入到app 组件中。我在另一个指南上看到这是一个没有解释的“有利”。
@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?
【问题讨论】:
-
I saw on another guide that this was a "favorable" without explanationhttp 更有利,因为http将被弃用。 -
关于2,见stackoverflow.com/questions/38213995/…。由于 HttpClient 的设计方式,您将很难做到这一点。通常使用单个 HttpClient 实例。
-
关于#2,参见Dependency Injection - When to use NgModule versus an application component。您可以在组件中指定提供程序,并为该组件及其子组件提供一个新实例。
标签: angular dependency-injection angular-httpclient