Search code examples
angularinterceptoridentityserver4angular-http-interceptors

Angular HttpInterceptor intercept method does not work with the first request


I am tring to pass the authentication token with the header in the request using the HttpInterceptor intercept method. My _loginSvr gives the token from the Observable returned from the GetUser() method. So when the next.handle(request) is returned at that time token is empty. But in the next http request it works as the token has been feteched already I guess from the previous request. So how can I wait for handle to return the reuqest until I have gotten the token.

enter image description here


Solution

  • Because subscribe is 'non-blocking' the line return next.handle(request); is reached before the subscribe method is completed:

    You could use a mergeMap here:

    import 'rxjs/add/operator/mergeMap';
    
    ...
    
    intercept(req: HttpRequest<any>, next: HttpHandler) {
        return this._loginSvr.GetUser().mergeMap(user => {
            if (user.access_token) {
                req = req.clone({ setHeaders: { Authorization: 'Bearer ' + user.access_token } });
            }
            return next.handle(req);
        }
    }
    

    Handling your login logic could be implemented inside the mergeMap functionallity.