准备
在AppModule中导入HttpClientModule
import { HttpClientModule } from '@angular/common/http';@NgModule({imports: [HttpClientModule,],
注入依赖项
// app/config/config.service.tsimport { Injectable } from '@angular/core';import { HttpClient } from '@angular/common/http';@Injectable()export class ConfigService {constructor(private http: HttpClient) { }}
从服务器请求数据
使用 HTTPClient.get() 方法从服务器获取数据。该异步方法会发送一个 HTTP 请求,并返回一个 Observable,它会在收到响应时发出所请求到的数据。返回的类型取决于你调用时传入的 observe 和 responseType 参数。get()方法有两个参数,一个string类型的url,一个可以用来配置请求的选项对象
options: {headers?: HttpHeaders | {[header: string]: string | string[]},observe?: 'body' | 'events' | 'response', // 指定要返回的响应内容,默认为"body"params?: HttpParams|{[param: string]: string | string[]},reportProgress?: boolean,responseType?: 'arraybuffer'|'blob'|'json'|'text', // 指定返回数据的格式,默认为"json"withCredentials?: boolean,}
