Angular6筆記之封裝http

ma125120發表於2018-07-26

最近抽空學習了一下Angular6,之前主要使用的是vue,所以免不了的也想對Angular6提供的工具進行一些封裝,今天主要就跟大家講一下這個http模組。

之前使用的ajax庫是axios,可以設定baseurl,公共頭部;集中捕捉錯誤等,由於Angular6的依賴注入機制,是不能通過直接修改http模組暴露的變數來封裝的,但是通過官方文件我們知道可以通過攔截器(HttpInterceptor)來實現這一功能。 攔截器可以攔截請求,也可以攔截響應,那麼通過攔截請求就可以實現 設定baseurl,公共頭部;而通過攔截響應就可以實現 集中捕獲錯誤 。廢話不多說,上程式碼吧。

第一步:準備工作,匯入 HttpClientModule

在app.module.ts中匯入 HttpClientModule,然後在imports陣列中將 HttpClientModule 加入到 BrowserModule 之後,具體程式碼為:

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // import HttpClientModule after BrowserModule.
    HttpClientModule,
  ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [ AppComponent ]
})
複製程式碼

第二步:新建有關攔截器的檔案

在app資料夾下新建http-interceptors資料夾,在其內新建base-interceptor.ts,index.ts兩個檔案。其中,base-interceptor.ts是用於設定攔截器的注入器檔案,index.ts則為擴充套件攔截器的提供商。

### base-interceptor.ts

import { Injectable } from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest,
  HttpErrorResponse
} from '@angular/common/http';
import { throwError } from 'rxjs'
import { catchError, retry } from 'rxjs/operators';

/*設定請求的基地址,方便替換*/
const baseurl = 'http://localhost:8360';

@Injectable()
export class BaseInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(req, next: HttpHandler) {

    let newReq = req.clone({
      url: req.hadBaseurl ? `${req.url}` : `${baseurl}${req.url}`,
    });
    /*此處設定額外的頭部,token常用於登陸令牌*/
    if(!req.cancelToken) {
	  /*token資料來源自己設定,我常用localStorage存取相關資料*/
      newReq.headers =
      newReq.headers.set('token', 'my-new-auth-token')
    }

    // send cloned request with header to the next handler.
    return next.handle(newReq)
      .pipe(
        /*失敗時重試2次,可自由設定*/
        retry(2),
        /*捕獲響應錯誤,可根據需要自行改寫,我偷懶了,直接用的官方的*/
        catchError(this.handleError)
      )
  }
  
  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  };
}


### index.ts

import { HTTP_INTERCEPTORS } from '@angular/common/http';

import { BaseInterceptor } from './base-interceptor';

/** Http interceptor providers in outside-in order */
export const httpInterceptorProviders = [
  { provide: HTTP_INTERCEPTORS, useClass: BaseInterceptor, multi: true },

];

/*
Copyright 2017-2018 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
複製程式碼

通過克隆修改 req 物件即可攔截請求,而操作 **next.handle(newReq)**的結果即可攔截響應。如果需要修改,可直接擴充套件 base-interceptor.ts或 參考 base-interceptor.ts 檔案新建其他檔案,然後在 index.ts 中正確引入該攔截器,並將其新增到 httpInterceptorProviders 陣列中即可。

第三步:註冊提供商

在app.module.ts中加入以下程式碼:

import { httpInterceptorProviders } from './http-interceptors/index'

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [
    httpInterceptorProviders
  ],
  bootstrap: [AppComponent]
})

複製程式碼

第四步,提取baseurl

為了方便後臺修改baseurl,我們可以將baseurl提取為全域性變數,在index.html中進行設定,

# index.html 增加
<script>
  window.baseurl = "http://localhost:8360"
</script>

# base-interceptor.ts 修改
const baseurl = window.baseurl;
複製程式碼

這樣一來,如果後臺要修改的話,只需修改index.html中的變數即可,無需再次編譯(感謝 _John 的提醒)。還有,像這些後期可能更改的變數,建議是直接放在index.html中,因為快取的原因,如果放在js檔案中再引入的話,檔案並不能及時更新或是每次都需要更改檔名,會導致不必要的麻煩。

至此,Angular6的http模組封裝已經基本完成,如果有需要可以自行擴充套件,可參考第二步。如果看完以後不明白或者我有寫的不對的地方,歡迎大家在下方進行評論。

相關文章