发布于 1年前

Angular HttpClient请求JSON和非JSON数据

从Angular 4开始,Angular的http请求改用HttpClient。

添加HttpClientModule

首先需要引入HttpClientModule,它需要放在BrowserModule后:

import { NgModule }         from '@angular/core';
import { BrowserModule }    from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule,
  ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

请求JSON数据

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ConfigService {
  constructor(private http: HttpClient) { }
  getData() {
    return this.http.get(this.dataUrl);
  }
}

HttpClient其中一个特性是默认返回的数据为json数据。,使用它返回的数据如下:

http.get(url).subscribe(...)

对于angular 4之前,则需要做json转换:

http.get(url).map(res => res.json()).subscribe(...)

请求非JSON数据

如果需要返回非JSON数据,则需要在请求时设置responseType头信息为text:

getTextFile(filename: string) {
  return this.http.get(filename, {responseType: 'text'})
    .pipe(
      tap( 
        data => this.log(filename, data),
        error => this.logError(filename, error)
      )
    );
}

http.get()返回的是一个Observable<String>

©2020 edoou.com   京ICP备16001874号-3