您好,登錄后才能下訂單哦!
這篇文章給大家介紹Angular6封裝http,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
第一步:準備工作,導入 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] })
關于Angular6封裝http就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。