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 ]
})
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值