Angular 2+ HttpIntercept: wait for token from server before returning intercept function

angular 7 refresh token interceptor
angular conditional interceptor
angular 6 interceptor example
angular 6 http interceptor example
angular interceptor refresh token
what is interceptor in angular 4
angular http interceptor example
angular-http interceptor error handling

I know that this question has been addressed in one way/shape/form before, but I've reviewed all the questions and answers I can find, and still I cannot figure out how to solve this problem.

HttpIntercept.intercept has to return next.handle(request). However, I need it to wait (I know "wait" is a dirty word in front end) for the bearer token to come back from the server before it can return. I can't for the life of me find a pattern that accomplishes this. The intercept function cannot return until we have made a trip to the server to get a bearer token.

If this has been answered, I apologize, please provide me the link to the appropriate answer.

Non-working example (function returns before token is appended):

export class TokenInterceptor implements HttpInterceptor {
  constructor(private auth: AuthenticationService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let token: string;
    this.auth.getToken().subscribe(response => {
      token = response['access_token'];
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${token}`
        }
      });
    });

    return next.handle(request);
  }
}

Use switchMap to return Observable from anther Observable.

export class TokenInterceptor implements HttpInterceptor {
  constructor(private auth: AuthenticationService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let token: string;
    return this.auth.getToken().switchMap(response => {
      token = response['access_token'];
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${token}`
        }
      });

       return next.handle(request);
    });
  }
}

Angular 2+ HttpIntercept: wait for token from server before - html, The intercept function cannot return until we have made a trip to the server to get a bearer token. If this has been answered, I apologize, please provide me the  The general idea standing behind JWT is to securely transmit information between parties. In our case, it is the user’s identity along with his rights, transmitted between the client (browser) and the server. When the user logs in, sending login query to the server, he receives back a JWT (aka access token) signed by the server with a private


I can think of something like:

export class TokenInterceptor implements HttpInterceptor {
  constructor(private auth: AuthenticationService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return this.auth.getToken()
        .map(response => request.clone({setHeaders: {Authorization: `Bearer ${response['access_token']}`}}))
        .switchMap(request => next.handle(request));
  }
}

Although I am not sure it would work.

Top 10 ways to use Interceptors in Angular, There are many ways to use an interceptor, and I'm sure most of us have only In this article, I will present my ten favorite ways to use interceptors in Angular. Everyone wants to see the spinning wheel of fortune when we are waiting for a For this, we can use a loader service that has a show and a hide function. Before​  For example, appending the authentication token to every HTTP request and that token is generated from the client who needs to be validated at the server for security purpose. These interceptors act as a hook up for the HTTP calls.


Your handler is being called synchronously while your request is asynchronous.

As you need to return an observable take a look into the flatMap/switchMap operator from rxjs, it would look something like:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let token: string;
    return this.auth.getToken().flatMap(response => {
      token = response['access_token'];
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${token}`
        }
      });
      return next.handle(request);
    });
}

Angular Tutorial, Until this version, there was no way to modify or to intercept http request globally. Jun 16, 2018 · 2 min read. This article explains how to implement a refresh token using HttpInterceptor in the new Angular return Observable.throw(error); When access token expire generally server send a 401 Unauthorized response. So the problem is until subscribe() method is invoked on this.auth.refreshAccessToken(), it wont trigger the GET/POST request to a server. Simply calling switchMap() didn't work in my case. And with subscribe, i have to unsubscribe it on some point to avoid memory leaks.


Try returning in the Observable completed function:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let token: string;
    this.auth.getToken().subscribe(response => {
      token = response['access_token'];
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${token}`
        }
      });
    },
    err => { console.log(err) },
    () => return next.handle(request) // this is called after the completion of observable
    );

  }
}

Insider's guide into interceptors and HttpClient mechanics in Angular , One of its major features was request interception — the ability to by adding Custom-Header-1 and Custom-Header-2 to the request: @Injectable() export class I1 implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HTTP handler registered in the DI container under HttpHandler token. Top shelf learning. Dev tutorials explaining the code and the choices behind it all.. Made with 💖 by @chrisoncode and Nick.


Angular 4 Tutorial, When you login, you get an authorization token and a refresh token. 2. 3. 4. 5. 6​. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22 how to call your refreshToken method on the server and store the results in session token to the Authorization header; In the intercept method, we return next.handle  Angular 6 Web API 2 Bearer Token Authentication add to header with HttpInterceptor 6 refresh token interceptor angular 6 http interceptor angular remove them


Angular Authentication: Using the Http Client and , Let's take a look at how to use Angular's HttpInterceptor interface to make authenticated HTTP requests. When handling authentication in an Angular app​, it's generally best to to use angular2-jwt to return a boolean after checking the exp claim. src/app/auth/token.interceptor.ts import { Injectable } from  Angular interceptor is familiar to AngularJS developers, but interceptors weren't supported in early angular versions. After Angular 4.3 they introduce the angular interceptor. In this post, you will learn how to use the Angular 6&amp;7 interceptor to


Intercepting Http Requests-- Using And Testing Angular's HttpClient , Intercepting Http Requests-- Using And Testing Angular's HttpClient Using angular-cli, I generated a new application and used Material 2 starter app as a public getUsers(): Observable<User[]> { return this.http.get<Array<any>>(this. it​('should throw with an error message when API returns an error',  The http interceptor is similar to a middleware function in Express or Spring Boot app. The HttpInterceptor interface was released with Angular v4.3. angular http interceptor examples: Here is a basic example of implementing the HttpInterceptor interface: