最近抽空學習了一下Angular6,以前主要使用的是vue,因此免不了的也想對Angular6提供的工具進行一些封裝,今天主要就跟你們講一下這個http模塊。
以前使用的ajax庫是axios,能夠設置baseurl,公共頭部;集中捕捉錯誤等,因爲Angular6的依賴注入機制,是不能經過直接修改http模塊暴露的變量來封裝的,可是經過官方文檔咱們知道能夠經過攔截器(HttpInterceptor)來實現這一功能。html
攔截器能夠攔截請求,也能夠攔截響應,那麼經過攔截請求就能夠實現 設置baseurl,公共頭部;而經過攔截響應就能夠實現 集中捕獲錯誤 。廢話很少說,上代碼吧。vue
在app.module.ts中導入 HttpClientModule,而後在imports數組中將 HttpClientModule 加入到 BrowserModule 以後,具體代碼爲:ios
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則爲擴展攔截器的提供商。ajax
### 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 數組中便可。bootstrap
在app.module.ts中加入如下代碼:axios
import { httpInterceptorProviders } from './http-interceptors/index' @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [ httpInterceptorProviders ], bootstrap: [AppComponent] })
爲了方便後臺修改baseurl,咱們能夠將baseurl提取爲全局變量,在index.html中進行設置,數組
# index.html 增長 <script> window.baseurl = "http://localhost:8360" </script> # base-interceptor.ts 修改 const baseurl = window.baseurl;
這樣一來,若是後臺要修改的話,只需修改index.html中的變量便可,無需再次編譯。還有,像這些後期可能更改的變量,建議是直接放在index.html中,由於緩存的緣由,若是放在js文件中再引入的話,文件並不能及時更新或是每次都須要更改文件名,會致使沒必要要的麻煩。緩存
至此,Angular6的http模塊封裝已經基本完成,若是有須要能夠自行擴展,可參考第二步。若是看完之後不明白或者我有寫的不對的地方,歡迎你們在下方進行評論。app