Angular 拦截器配置

官方文档

创建AuthInterceptor.ts文件

import { AuthService } from './../app.service';
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private authService: AppService) {}
  
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  	// 获取本地存储的token值,
    const authToken = this.authService.getAuthorizationToken();
    // 若token存在,则对请求添加请求头
    // 并格式化处理url地址,简化service中接口地址的编辑
    if (authToken) {
      const authReq = req.clone({
        headers: req.headers.set('Authorization', 'bearer' + authToken),
        url: environment.api_endpoint + req.url
      });
      return next
      // 返回处理后的请求
      .handle(authReq) 
      // 返回结果错误处理
      .pipe(catchError(error => this.auth.handleError(error)));
    }
    // 若token不存在,则不对请求进行处理
    return next.handle(req);
  }
}

挂载authInterceptor.ts文件

// 一般在主模块中注入,使系统所有请求都被拦截
@ngModule({
	declarations: [],
	imports:[],
	providers: [
		{
			provide: HTTP_INTERCEPTORS,
	      	useClass: AuthInterceptor,
	      	multi: true
		}
	]
})

允许创建多个拦截器

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { NoopInterceptor } from './noop-interceptor';
import { AuthInterceptor } from './authInterceptor';
// 将多个拦截器添加至一个List中,然后一次性挂载
export const httpInterceptorProviders = [
  { provide: HTTP_INTERCEPTORS, useClass: NoopInterceptor, multi: true },
  { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
];
import { httpInterceptorProviders } from './httpInterceptorProviders.ts'
@ngModule({
	declarations: [],
	imports:[],
	providers: [ httpInterceptorProviders ]
})

你可能感兴趣的:(Angular)