1

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

et3rnal
  • 322
  • 4
  • 17
  • By subscribing to `next.handle(OrgReq)` I got it to execute it after login, however, the component that which fired the request doesn't know as its request has already unsubscribed with the 401. Is this how this suppose to work? can't I get it to continue? – et3rnal Oct 09 '19 at 04:34

1 Answers1

2

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

Robert garcia
  • 581
  • 2
  • 7
  • Thanks, I have updated the answer with what I tried, can you please have a look and tell me if what I'm thinking is right and if so how to prevent that – et3rnal Oct 09 '19 at 01:13
  • Thanks @Robert, help me to understand how to intercept/catch request – Camille Jul 13 '21 at 09:12