1.導(dǎo)入 HttpClientModule
app.module.ts中導(dǎo)入 HttpClientModule
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
],
declarations: [
AppComponent,
],
bootstrap: [ AppComponent ]
})
2.新建有關(guān)攔截器的文件
在app文件夾下新建http-interceptors文件夾,在其內(nèi)新建base-interceptor.ts绎巨,index.ts兩個(gè)文件朱转。其中,base-interceptor.ts是用于設(shè)置攔截器的注入器文件,index.ts則為擴(kuò)展攔截器的提供商耘擂。
### 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';
/*設(shè)置請(qǐng)求的基地址蓖租,方便替換*/
const baseurl = 'http://localhost:5000';
@Injectable()
export class BaseInterceptor implements HttpInterceptor {
constructor() {}
intercept(req, next: HttpHandler) {
let newReq = req.clone({
url: req.hadBaseurl ? `${req.url}` : `${baseurl}${req.url}`,
//簡(jiǎn)寫(xiě)
setHeaders: { Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjEzNjIwNjc2NTUwIiwiaWQiOjEsImVtYWlsIjoiMTMyNTY0IiwiaWF0IjoxNTY2Mjg0MzQ4LCJleHAiOjE1NjYzMDIzNDh9.MC2xUGMRwMFRJuDniZ--sm0-ZxVsJcc5fuQZZTz8OyA' }
});
/*此處設(shè)置額外的頭部,token常用于登陸令牌*/
// if(!req.cancelToken) {
// /*token數(shù)據(jù)來(lái)源自己設(shè)置饭玲,我常用localStorage存取相關(guān)數(shù)據(jù)*/
// newReq.headers = newReq.headers.set('Authorization', 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjEzNjIwNjc2NTUwIiwiaWQiOjEsImVtYWlsIjoiMTMyNTY0IiwiaWF0IjoxNTY2Mjg0MzQ4LCJleHAiOjE1NjYzMDIzNDh9.MC2xUGMRwMFRJuDniZ--sm0-ZxVsJcc5fuQZZTz8OyA')
// // newReq.headers = newReq.headers.set('token', 'my-new-auth-token')
// }
// send cloned request with header to the next handler.
return next.handle(newReq)
.pipe(
/*失敗時(shí)重試2次侥祭,可自由設(shè)置*/
retry(2),
/*捕獲響應(yīng)錯(cuò)誤,可根據(jù)需要自行改寫(xiě),我偷懶了矮冬,直接用的官方的*/
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 },
];
3.注冊(cè)提供商
在app.module.ts中加入以下代碼:
import { httpInterceptorProviders } from './http-interceptors/index'
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [
httpInterceptorProviders
],
bootstrap: [AppComponent]
})