Wesley
Wesley

Reputation: 317

An angular http interceptor for each 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?

Upvotes: 0

Views: 854

Answers (1)

Brandon Avilan
Brandon Avilan

Reputation: 56

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)),
          );
        }

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)),
          );
        }

Upvotes: 1

Related Questions