title: How can I redirect to login page on 401 response in Angular 5?
body: <p>I'm working on a Angular 5 application using OAuth2 implicit flow.</p>
  
  <p>I have services that perform HTTP calls, following one example of my services:</p>
  
  <pre><code>@Injectable()
  export class MyService {
  
    constructor(public http: HttpClient) { }
  
    public getAll(): Observable&lt;Persona[]&gt; {
      return this.http.get&lt;Persona[]&gt;("http://mywebservice/persone");
    }
  }
  </code></pre>
  
  <p>I'm using interceptors for authorization and add custom attributes. Following my auth interceptor:</p>
  
  <pre><code>import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
  import { Injectable } from '@angular/core';
  import { Observable } from "rxjs";
  
  @Injectable()
  export class AuthInterceptor implements HttpInterceptor {
  
    constructor() {
  
    }
    intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
      let accessToken = sessionStorage.getItem("access_token");
      if(accessToken)
      {
          request = request.clone({
          setHeaders: {
              Authorization: `Bearer ${accessToken}`
          }
          });
      }
  
      return next.handle(request);
    }
  }
  </code></pre>
  
  <p>And following how I consume my services:</p>
  
  <pre><code>public myMethod() {
      this.myService.getAll().subscribe(
          result =&gt; {
              console.log(result);
          }, error =&gt; {
              // I don't want add redirection there...
              console.error(error);
          });
  }
  </code></pre>
  
  <p>Now my need is that when any HTTP call receive 401 result, the application redirects the user to login page. </p>
  
  <p>How can I obtain this result without code duplication?</p>
  
  <p>Thank you a lot</p>