title: Angular redirect page if HTTP response is 401
body: <p>I'm sending multiple API requests in my Angular (10) app. If one of the requests returns response with status 401 I would like to redirect the page to my login page (from the component page).</p>
  <p>I have a service that responsible for API calls that has the following 2 methods :</p>
  <pre><code>    export class ApiService {
      constructor(private http: HttpClient){
  }
        public get&lt;T&gt;(path: string, params: HttpParams = new HttpParams(), headers: HttpHeaders = new HttpHeaders()): Observable&lt;T&gt; {
          return this.getBodyOfResponseOrRedirect(
            this.http.get&lt;T&gt;(path, {headers, params, observe: 'response'}));
        }
      
        private getBodyOfResponseOrRedirect&lt;T&gt;(responseObservable: Observable&lt;HttpResponse&lt;T&gt;&gt;): Observable&lt;T&gt; {
          return responseObservable.pipe(map(response =&gt; {
            if (response.status === 401) {
              window.location.href = 'https://custom-url';
            } else {
              return response.body;
            }
          }));
        }
  </code></pre>
  <p>Now I tried using the API service methods in another service:</p>
  <pre><code> export class ShopDataService{
    ...
    getShopsData(): Observable&lt;Shop[]&gt; {
      return this.apiService.get&lt;Shop[]&gt;(&quot;https://shops.com/v1/endpoint)
        .pipe(
          tap(data =&gt; console.log('shop recieved : ' + JSON.stringify(data))),
          catchError(this.handleError)
        );
    }
  
    private handleError(err: HttpErrorResponse) {
      let errorMessage = '';
      errorMessage = `Server returned code : ${err.status}, error message is : ${err.message}`;
      console.error(errorMessage);
      return throwError(errorMessage);
    }
  </code></pre>
  <p>The redirect doesn't work when the response status is 401, instead I'm seeing in the console :</p>
  <blockquote>
  <p>main.gb7558h03a743440f512.js:1 Server returned code : 401, error message is : Http failure response for <a href="https://shops.com/v1/endpoint" rel="nofollow noreferrer">https://shops.com/v1/endpoint</a>: 401 OK</p>
  </blockquote>
  <p>What am I doing wrong ?</p>
  <p>The big idea here, is that when I load the component my auth token is valid. After some time, my token is expired but I didn't refresh or move to another page. Therefore, current page functionality might send api requests with an invalid token and will get 401 error in response. I would like to handle this behavior.</p>