Angular 8 intercept 401 with login modal

1.1k Views Asked by At

I'm trying to get the user to continue where they left off by entering the login details from anywhere in the app, however, I don't have a token or refresh token, the backend uses session cookie.

Here is what I'm trying to do without success so far, using HttpInterceptor, once the response is 401 I show a modal using ngx-bootstrap modal service.

The above part relatively works, now I'm not sure how can get the service/intercept to request the same request that failed.

I tried to do the same thing without the interceptor without luck.

Any ideas or example would be great.


Update: I still can't get it to work retryWhen didn't help

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      retryWhen(errors =>
        errors.pipe(
          tap(errorStatus => {
            let OrgReq;
            console.log("tap: ", errorStatus);
            if (errorStatus.status === 401) {
              OrgReq = req.clone();
              this.authModalRef = this.modalService.show(AuthenticationComponent, this.initialState);  
              this.authModalRef.content.onLoggedIn.subscribe(loggedIn => {
                    console.log("has logged? ", loggedIn, OrgReq);
                    return next.handle(OrgReq);
                });
            }

            throw errorStatus;

          })
        )
      )
  );
}

I think because the first request getting unsubscribed after the 401 the next.handle() isn't doing anything

1

There are 1 best solutions below

2
Robert garcia On

I think retryWhen pipe operator will do the trick for you

https://www.learnrxjs.io/operators/error_handling/retrywhen.html

Something like this:

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

        let clone = req.clone()

        return next.handle(clone).pipe(

            retryWhen(err => {
                // You can filter based on the error
                const retryReq = confirm("Retry");
                if(retryReq)return next.handle(clone)
                else return OtherObservable
            })
        );
    }
}

You need to return an Observable always either true or false is resolved