Angular使用Interceptor(拦截器)请求添加token并统一处理API错误

前后端分离的项目,大多都是无状态的,我们使用JSON Web Tokens进行身份验证,但是每次请求都手动添加token这种事情是不可能做的,因为懒,这里就要用到拦截器Interceptor

创建src/app/app-auth-interceptor.module.ts实现拦截器

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = this.storage.retrieve('token'); // token保存在localstorage
    if (token) { // 如果有token,就添加
      req = req.clone({
        setHeaders: {
          Authorization: `Bearer ${token.access_token}`
        }
      });
    }
    return next.handle(req).pipe(
      tap(event => {
        if (event instanceof HttpResponse) { // 这里是返回,可通过event.body获取返回内容
          // event.body
        }
      }, error => { // 统一处理所有的http错误
        if (error instanceof HttpErrorResponse) {
          if (error.status == 401) {
            this.router.navigate(['/index/login']);
          } else if (error.status == 500) {
            this.notification.create('error', '出错拉', '请求失败,请刷新页面试一试');
          } else if (error.status == 504) {
            this.notification.create('error', '重要提醒', '你当前的网络不稳定哦!');
          } else {
            // this.message.create('warning', error.error['message']);
            this.modalService.error({
              nzTitle: 'Error',
              nzContent: error.error.message ? error.error.message : error.message
            });
          }
        } else {
          this.notification.create('error', '出错拉', '网络请求错误,请刷新页面试一试');
        }
      })
    )
  }

src/app/app-routing.module.ts导入

import { AuthInterceptor } from './app-auth-interceptor.module';

并添加到providers

{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }

这样我们使用HttpClient的时候,如果有token就会自动添加header Authorization,返回http错误的时候,会弹窗提示错误信息。

《PHP微服务练兵》系列索引:https://blog.csdn.net/donjan/article/details/103005084

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值