每个API的角度HTTP拦截器 [英] An angular http interceptor for each API

查看:57
本文介绍了每个API的角度HTTP拦截器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我有3种不同的API用于不同的服务.每个API都有您自己的Auth令牌.我想创建3个HTTP拦截器,每个api一个.我知道为所有项目创建一个httpInterceptor,但是如何为每个api服务创建一个不同的拦截器?

Hello, I have 3 different apis for different services. Each API has you own Auth Token. I want to create 3 http interceptors, one for each api. I know create a httpInterceptor for all project, but how I can create a different interceptor for each api service?

推荐答案

您可以使用一个拦截器,并且由于在此拦截器中您可以读取URL,因此您可以创建一个函数,并根据此函数使用不同的令牌,例如:

You can use a single interceptor, and since in this one you have access to read the URL, you can create a function that depending on this uses a different token, for example:

        intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
          let token;
          
          if (request.url.indexOf(PATH_ROUTE_ONE) !== -1) {
            token =  localStorage.getItem(TK1);
          } else if(request.url.indexOf(PATH_ROUTE_TWO) !== -1) {
            token =  localStorage.getItem(TK2);
          } else {
            token =  localStorage.getItem(TK3);
          }

          if (token) {
            request = request.clone({
              setHeaders: {
                authorization: `Bearer ${token}`,
              },
            });
          }

          return next.handle(request).pipe(
            tap((res) => {
              if (res instanceof HttpResponse) {
                // TODO: Update token info
              }
            }),
            catchError((err: HttpErrorResponse) => throwError(err)),
          );
        }

如果您想使用3条路径,可以做同样的事情,并且只读取URL即可知道是应用该URL还是让它继续长时间运行

If you want to use 3 paths you can do the same and you only read the URL to know if you apply it or let it continue long

       intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
          let token = localStorage.getItem(TK1)
          
          if (request.url.indexOf(PATH_ROUTE_ONE) !== -1) {
            request = request.clone({
              setHeaders: {
                authorization: `Bearer ${token}`,
              },
            });
          }

          return next.handle(request).pipe(
            tap((res) => {
              if (res instanceof HttpResponse) {
                // TODO: Update token info
              }
            }),
            catchError((err: HttpErrorResponse) => throwError(err)),
          );
        }

这篇关于每个API的角度HTTP拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆