准备

在AppModule中导入HttpClientModule

  1. import { HttpClientModule } from '@angular/common/http';
  2. @NgModule({
  3. imports: [
  4. HttpClientModule,
  5. ],

注入依赖项

  1. // app/config/config.service.ts
  2. import { Injectable } from '@angular/core';
  3. import { HttpClient } from '@angular/common/http';
  4. @Injectable()
  5. export class ConfigService {
  6. constructor(private http: HttpClient) { }
  7. }

从服务器请求数据

使用 HTTPClient.get() 方法从服务器获取数据。该异步方法会发送一个 HTTP 请求,并返回一个 Observable,它会在收到响应时发出所请求到的数据。返回的类型取决于你调用时传入的 observeresponseType 参数。
get()方法有两个参数,一个string类型的url,一个可以用来配置请求的选项对象

  1. options: {
  2. headers?: HttpHeaders | {[header: string]: string | string[]},
  3. observe?: 'body' | 'events' | 'response', // 指定要返回的响应内容,默认为"body"
  4. params?: HttpParams|{[param: string]: string | string[]},
  5. reportProgress?: boolean,
  6. responseType?: 'arraybuffer'|'blob'|'json'|'text', // 指定返回数据的格式,默认为"json"
  7. withCredentials?: boolean,
  8. }