angular http拦截响应

1.导入 HttpClientModule

app.module.ts中导入 HttpClientModule

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

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

2.新建有关拦截器的文件

在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:5000';

@Injectable()
export class BaseInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(req, next: HttpHandler) {

    let newReq = req.clone({
      url: req.hadBaseurl ? `${req.url}` : `${baseurl}${req.url}`,
      //简写
      setHeaders: { Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjEzNjIwNjc2NTUwIiwiaWQiOjEsImVtYWlsIjoiMTMyNTY0IiwiaWF0IjoxNTY2Mjg0MzQ4LCJleHAiOjE1NjYzMDIzNDh9.MC2xUGMRwMFRJuDniZ--sm0-ZxVsJcc5fuQZZTz8OyA' }
    });
    /*此处设置额外的头部,token常用于登陆令牌*/
    // if(!req.cancelToken) {
    //   /*token数据来源自己设置,我常用localStorage存取相关数据*/
    //   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(
        /*失败时重试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 },

];

3.注册提供商

在app.module.ts中加入以下代码:

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

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

你可能感兴趣的:(angular http拦截响应)