title: Angular 7 - How can I share the token renewal Observable?
body: <p>Before each request a HTTP interceptor checks if the access token is expired and if so, it first renews the token and then continues the request.</p>
  
  <p>The problem is on pages that have multiple requests. On those pages the interceptor tries to renew the token for each request.</p>
  
  <p>How can I share the token renewal request in this case?</p>
  
  <p>The method that is responsible for token renewal is this:</p>
  
  <pre><code>renewToken() {
  
      let refreshToken = // get refresh token
  
      let accessToken = // get access token
  
      if (!refreshToken || !accessToken)
        return;
  
      let requestData = {
        accessToken: accessToken,
        refreshToken: refreshToken
      }
  
      return this.http.post&lt;ApplicationToken&gt;(`${this.baseUrl}/renewToken`, requestData)
        .pipe(
          // I tried share() shareReplay(1) and publishReplay(1) here but no luck
        );
  }
  </code></pre>
  
  <p>And this is how the interceptor uses that method:</p>
  
  <pre><code>...
  // in case we need to renew the token
  return this.accountService.renewToken()
    .pipe(                        
      switchMap(t =&gt; {
  
        this.accountService.saveToken(t);
        token = this.accountService.getAccessToken();
  
        var newReq = this.setToken(req, token);
        return next.handle(newReq);
      })
    );
  ...
  </code></pre>