Angular2 HttpClient (一)


  @angular/common/http 中的 HttpClient 類為 Angular 應用程序提供了一個簡化的 API 來實現 HTTP 客戶端功能。它基於瀏覽器提供的 XMLHttpRequest 接口。 HttpClient 帶來的其它優點包括:可測試性、強類型的請求和響應對象、發起請求與接收響應時的攔截器支持,以及更好的、基於可觀察(Observable)對象的 API 以及流式錯誤處理機制。

准備工作

  1、要想使用 HttpClient,就要先導入 Angular 的 HttpClientModule。大多數應用都會在根模塊 AppModule中導入它。

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 { }

  2、在 AppModule 中導入 HttpClientModule 之后,將HttpClient注入到應用類中。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ConfigService { constructor(private http: HttpClient) { }
}

獲取 JSON 數據

  config.json文件:

{
  "heroesUrl": "api/heroes",
  "textfile": "assets/textfile.txt"
}

 

  1、通過 HttpClient 的 get() 方法獲取Json數據,如下:

configUrl = 'assets/config.json';

getConfig() {
  return this.http.get(this.configUrl);
}

  2、將 服務service 注入到組件中,並調用其 getConfig 方法。

 
         
config: Config;
showConfig() {
  this.configService.getConfig()
    .subscribe((data: Config) => this.config = {
        heroesUrl: data['heroesUrl'],
        textfile:  data['textfile']
    });
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM