title: Angular 4 - intercept http request and resend after login
body: <p>I have an <code>HttpInterceptor</code> which listens to specific JWT token events (<code>token_expired</code>, <code>token_not_provided</code> and <code>token_invalid</code>) that can happen at different times of the workflow. </p>
  
  <p>These events can happen when a user navigates to a different route OR when an AJAX request is being sent while in the same route (like retrieving data, saving a form, etc).</p>
  
  <p>When the interceptor detects any of those specific events, it prompts the user to enter login credentials again (using a modal) and queues the request for later processing (after user logged in again). This is important since the data which was submitted can not be lost (e.g. when updating an order or a customer).</p>
  
  <p>A Simplified version of my interceptor code is:</p>
  
  <pre><code>@Injectable()
  export class AuthInterceptor implements HttpInterceptor {
      constructor(private injector: Injector) {}
      router: Router;
      auth: AuthService;
      api: APIService;
      intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
          this.router = this.injector.get(Router);
          this.auth = this.injector.get(AuthService);
          let token = this.auth.getToken();
          let headers = {
              'Content-Type':'application/json',
          };
          if (token) {
              (&lt;any&gt;headers).Authorization =  `Bearer ${token}`;
          }
  
          request = request.clone({
              setHeaders: headers
          });
          return next.handle(request).do((event: HttpEvent&lt;any&gt;) =&gt; {
  
          }, (err: any) =&gt; {
              if (err instanceof HttpErrorResponse) {
                  let msg = typeof(err.error) === 'string' ? JSON.parse(err.error) : err.error;
                  if (msg &amp;&amp; msg.error &amp;&amp; ['token_not_provided', 'token_expired','token_invalid'].indexOf(msg.error) &gt; -1) {
                          this.auth.queueFailedRequest(request);
                          //set the intended route to current route so that after login the user will be shown the same screen
                          this.auth.setIntendedRoute(this.router.url);
                          //show the login popup
                          this.auth.promptLogin();
                      }
                  }
              }
          });
      }
  }
  </code></pre>
  
  <p>The relevant part of AuthService is:</p>
  
  <pre><code> queue: Array&lt;HttpRequest&lt;any&gt;&gt; = [];
   queueFailedRequest(request): void {
      this.queue.push(request);
   }
  
   retryFailedRequests(): void {
          this.queue.forEach(request =&gt; {
              this.retryRequest(request);
          });
          this.queue = [];
   }
   retryRequest(request): void {
          if (request.method === 'GET') {
               this.apiService.get(request.urlWithParams);
          }
          else if (request.method === 'POST') {
               this.apiService.post(request.urlWithParams, request.body || {});
          }
      }
  </code></pre>
  
  <p>And, of course, after a successful login I call the <code>retryFailedRequests()</code>.</p>
  
  <p>So far so good and indeed all HTTP requests are being queued and sent if a login is successful.</p>
  
  <p>And now to the problem - if the code is stuctured as in this example (taken from an <code>EditOrder</code> component):</p>
  
  <pre><code>updateOrder() {
     this.api.updateOrder(this.data).subscribe(res =&gt; {
       if (res.status === 'success') {
          alert('should be triggered even after login prompt');
       }
    });
  }
  </code></pre>
  
  <p>Then, if the user needs to re-login in the process, the alert will never be triggered once the <code>retryFailedRequests()</code> method finished processing the queue.</p>
  
  <p>So the question is what is the best way to make sure that the original promise is queued along with the HTTP request and resolved when the queue finished processing?</p>