zomdar
zomdar

Reputation: 273

testing angular interceptor (loading-spinner)

I'm trying to test an http interceptor in angular v10 and i'm having trouble getting started. The interceptor takes an http requests and triggers a spinner (loadService) until the response comes back. I have an interceptor that looks like this. Most of the interceptor articles that i've read are mostly with interceptors with headers and what not.

  removeRequest(req: HttpRequest<any>) {
    const i = this.requests.indexOf(req);
    if (i >= 0) {
      this.requests.splice(i, 1);
    }
    this.loaderService.isLoading.next(this.requests.length > 0);
  }

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    this.requests.push(req);

    this.loaderService.isLoading.next(true);
    return new Observable((observer) => {
      const subscription = next.handle(req).subscribe(
        (event) => {
          if (event instanceof HttpResponse) {
            this.removeRequest(req);
            observer.next(event);
          }
        },
        (err) => {
          this.removeRequest(req);
          observer.error(err);
        },
        () => {
          this.removeRequest(req);
          observer.complete();
        }
      );
      // remove request from queue when cancelled
      return () => {
        this.removeRequest(req);
        subscription.unsubscribe();
      };
    });
  }

can someone help me point me in the right direction?

Upvotes: 0

Views: 1009

Answers (1)

zehurzeda
zehurzeda

Reputation: 29

You are in the right way!

You only made a mistake in the intercept function, do the following:

intercept(req: HttpRequest<any>, next: HttpHandler) {

let updatedRequest: HttpRequest<any>;
updatedRequest = req.clone(//Add headers here);
this.loaderService.isLoading.next(true);

//Add the request at the array
this.requests.push(updatedRequest);

//You don't need to return new Observable, just handle with 'next' and pipes
return next.handle(updatedRequest).pipe(
  catchError((error: HttpErrorResponse) => {
    if (error.status >= 500) {
      console.log('error', error);
    }
    this.removeRequest(updatedRequest);
    return throwError(error);
  }),
  finalize(() => {
    this.removeRequest(updatedRequest);
  })
 );
}

Upvotes: 1

Related Questions