S
S
sdgroup142018-07-18 14:48:06
Angular
sdgroup14, 2018-07-18 14:48:06

How to make additional functions with Anular Interceptor?

In general, I had a task to make a chain of requests. 1 after another. For example, by clicking on the "item" I make 3 requests ... (ZY api can not do it differently). When receiving data, I stuff these 3 widgets ... ... In general, I have a template function and looks like this ($target is Subject Rxjs):

httpGetTemplate(param_url?, target?, arrCheck?) {
    const httpHandler = () => {
      const $params = param_url;
      const $target = target;
      const options = {
        headers: new HttpHeaders().set('Authorization', 'Bearer ' + localStorage.getItem('token'))
      };

      this.http.get(this.apiURL + $params, options).subscribe((_data: any) => {
        if (arrCheck) {
          const $data = _data.result;
          if ($target === this.allCategories) {
            this.allCategoriesCollection = $data;
          } else if ($target === this.checkFirebaseConnection) {
            this.checkFire = $data;
          }
        }
        $target.next(_data.result);
      }, _error => {
        console.log(_error);
        this.errorsHandler(_error, httpHandler);
      });
    };
    httpHandler();
  }

Crooked, but it worked.
And then I found Angular Interceptor. And such an article . I liked it there
// src/app/auth/jwt.interceptor.ts
// ...
import 'rxjs/add/operator/do';
export class JwtInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
    return next.handle(request).do((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        // do stuff with response if you want
      }
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        if (err.status === 401) {
          // redirect to the login route
          // or show a modal
        }
      }
    });
  }
}
This is also a great spot to cache any failed requests. This comes in handy if we have token refreshing in place and we want to retry the requests once we have a new token.

// src/app/auth/auth.service.ts
import { HttpRequest } from '@angular/common/http';
// ...
export class AuthService {
cachedRequests: Array<HttpRequest<any>> = [];
public collectFailedRequest(request): void {
    this.cachedRequests.push(request);
  }
public retryFailedRequests(): void {
    // retry the requests. this method can
    // be called after the token is refreshed
  }
}

// src/app/auth/jwt.interceptor.ts
// ...
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {    
  return next.handle(req).do((event: HttpEvent<any>) => {
    if (event instanceof HttpResponse) {
      // do stuff with response if you want
    }
  }, (err: any) => {
    if (err instanceof HttpErrorResponse {
      if (err.status === 401) {
        this.auth.collectFailedRequest(request);
      }
    }
  });
}

But the fact is that I don’t understand how to then call retryFailedRequests in turn when the token is updated .... Plus, I also put it in subscribe $target.next (data) which I stuff into several components ... How do I describe that I stuffed not a request a function into collectFailedRequest or maybe I don’t understand how to do it right? If someone does not understand why in subscribe $target.next (data). I did this in order not to make 3 requests for 3 widgets. Help plz :)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question