@angular/common/http 中的 HttpClient 类为 Angular 应用程序提供了一个简化的 API 来实现 HTTP 客户端功能。它基于浏览器提供的 XMLHttpRequest 接口。 HttpClient 带来的其它优势包括:可测试性、强类型的请求和响应对象、发起请求与接收响应时的拦截器支持,以及更好的、基于可观察(Observable)对象的 API 以及流式错误处理机制。json
一、要想使用 HttpClient
,就要先导入 Angular 的 HttpClientModule
。大多数应用都会在根模块 AppModule
中导入它。bootstrap
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule} from '@angular/common/http'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, // import HttpClientModule after BrowserModule. HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
二、在 AppModule
中导入 HttpClientModule
以后,将HttpClient注入到应用类中。api
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class ConfigService { constructor(private http: HttpClient) { } }
config.json文件:浏览器
{ "heroesUrl": "api/heroes", "textfile": "assets/textfile.txt" }
一、经过 HttpClient 的 get() 方法获取Json数据,以下:app
configUrl = 'assets/config.json'; getConfig() { return this.http.get(this.configUrl); }
二、将 服务service 注入到组件中,并调用其 getConfig
方法。ide
config: Config;
showConfig() { this.configService.getConfig() .subscribe((data: Config) => this.config = { heroesUrl: data['heroesUrl'], textfile: data['textfile'] }); }