Search code examples
angularangular8angular-routingangular-router

Perform http request before switching to next route


I want to perform a post request when navigating away from the page to any other route.

I have tried using:

  this.subscriptionGrade = router.events
      .pipe(filter((event) => event instanceof NavigationStart))
      .pipe(
        concatMap(() => {
          return this.submitScore();
        })
      )
      .subscribe((res) => {
        this.snackBar.openSnackBar("Score submitted", "");
      });


  submitScore() {
    const score = { score: this.scoreForm.get("score").value };
    if (this.scoreForm.get("score").value) {
      return this.learningContentService.gradeAssignment(
        this.selectedAttempt,
        score
      );
    } else {
      return of(null);
    }
  }

This performs the http reuquest but switches to next route before a response is recieved from the http request and the request is getting cancelled.


Solution

  • You can use canDeactivate on this route and check if the http call is successful or no

    export interface CanComponentDeactivate {
     canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
    }
    
    ...
    
    @Injectable()
    class CanDeactivateComponent implements CanDeactivate<CanComponentDeactivate>{
     constructor() {}
     canDeactivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
     let data= route.data.data;
     return this.service.post(url, data)
       .pipe(
         map(response => response.status === 'success'),
         catchError(error => of(false))
       );
     }
    }
    

    your route

    {
     path: 'yourRoute',
     component: Component,
     canActivate: [CanDeactivateComponent ],
     data: { data: {...}}
    }