title: How to prevent duplicated requests for interceptor in Angular?
body: <p>I have an <code>interceptor</code> which intercepts the <code>401</code> error codes received from a <code>200 OK</code> message.</p>
  <p>Unfortunately, I can't modify the <code>API</code> server to return <code>401</code> error instead of <code>200 OK</code> with error code.</p>
  <pre><code>intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
  return next.handle(request).pipe(
    switchMap((result: any) =&gt; {
      //401 unauthorized error message
      if (result &amp;&amp; result.body &amp;&amp; result.body.isSuccess == false &amp;&amp; result.body.errorCode == '401') {
        return this.unAuthorizedError(request, next);
      } else {
        return next.handle(request);
      }
    }),
    catchError((error) =&gt; {
      if (error instanceof HttpErrorResponse) {
        switch ((&lt;HttpErrorResponse&gt;error).status) {
          case 401:
          case 403:
            return this.unAuthorizedError(request, next);
          default:
            break;
        }
      }
      return throwError(error);
    })
  );
  }
  </code></pre>
  <p>The problem is that every request is send twice and I assume that this is <em>probably</em> due to <code>switchMap</code> method which returns <code>next.handle(request)</code>.</p>
  <p>I tried with <code>tap</code> method</p>
  <pre><code> tap((result: any) =&gt; {
      //401 unauthorized error message
      if (result &amp;&amp; result.body &amp;&amp; result.body.isSuccess == false &amp;&amp; result.body.errorCode == '401') {
        return this.unAuthorizedError(request, next);
      }
    }),
  </code></pre>
  <p>which sends the request only once, but when the token expires then <code>this.unAuthorizedError(request, next)</code> is not called.</p>