W
W
waltaki2019-10-05 20:19:46
Angular
waltaki, 2019-10-05 20:19:46

Angular intercept - how to do something when abort a request from outside?

Hello.
I have an intercept that, when a request appears, makes a loading animation on the page.
But, the problem is that when, for example, ngOnDestroy occurs on the page itself, and the request is unsubscribed, it is canceled (there is a call to abort the request), as a result of which, now I don’t know in intercept what is happening with this request, that is , I do not complete the animation, and it will be so indefinitely.

// component
private getUsersSubscription: Subscription;
ngOnInit() {
  this.getUsersSubscription = this.gsService.getUsers().subscribe(response => {
    // бла бла бла
  });
}

ngOnDestroy() {
  if(this.getUsersSubscription) this.getUsersSubscription.unsubscribe();
}

// intercept
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  
  this.visoad.startLoading();
  
  return next.handle(req).pipe(
    map((event: HttpEvent<any>) => {
      
      this.visoad.completeLoading();
      
      return event;
    }),
    catchError((err: any, caught) => {
      if (err instanceof HttpErrorResponse) {
        
        this.visoad.completeLoading();
        
        return observableThrowError(err);
      }
    })
  );
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2019-10-06
@waltaki

Strange, you have to end the animation as soon as the request is made. because first an HttpEvent with the Sent status will get into the map, it will always be regardless of the response.
And so here's what we managed to come up with https://stackblitz.com/edit/angular-m3quu3?file=sr...
not quite elegant, but it works, you can see which requests were canceled and which were successful.
Well, you should just complete the animation in finalize, regardless of the status.
By the way, what happens if there are several requests at the same time?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question