title: http-interceptor to wait for subscribe to finish getting data
body: <p>I am having an HTTP Interceptor. The backend API expects custom headers whose values are stored in indexdb during app initialization and other operations. Hence, I need to get the values and pass it with every request. But so far, failing to do so as the interceptor does not wait for the subscription to finish executing and sends requests without the custom headers.</p>
  
  <p>The intercetpor does get the currently saved or default headers but it is too late as the request goes thru without the headers.</p>
  
  <p>indexdb.service.ts:</p>
  
  <pre><code>@Injectable()
  export class IndexDBService {
    /*
      Handles configuration of the app:
          reading current configuration
          saving configuration
      */
  
    private pouch: any;
  
    constructor() {
      this.pouch = new PouchDB("config", {
        auto_compaction: true
      });
    }
  
    currentConfig(): Observable&lt;any&gt; {
      /*
        Return the current configuration saved in the database
      */
      let vm = this;
      return new Observable(observer =&gt; {
        vm.pouch.get("info", function(err, doc) {
          if (err) {
            console.log("config read error ", err);
            // create a default one
              configOptions={'header1': '1','header2':2}
             observer.next(configOptions);
          } else {
  
            observer.next(doc);
          }
        });
      });
    }
  }
  </code></pre>
  
  <p>interceptor.ts</p>
  
  <pre><code>import { Injectable } from "@angular/core";
  import {
    HttpEvent,
    HttpInterceptor,
    HttpHandler,
    HttpRequest,
    HttpHeaders
  } from "@angular/common/http";
  import { Observable } from "rxjs";
  import { IndexDBService } from "../services/indexdb.service";
  
  @Injectable()
  export class InterceptAPICalls implements HttpInterceptor {
    constructor(private indexdbService: IndexDBService) {}
  
    intercept(
      req: HttpRequest&lt;any&gt;,
      next: HttpHandler
    ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
  
      this.indexdbService.currentConfig().subscribe(configData =&gt; {
        console.log(configData); // ==&gt; does work great. I am getting data right
        req = req.clone({
          headers: new HttpHeaders({
  
            "X-Header1": configData["header1"],
            "X-Header2": configData["header2"]
          })
  
        });
        return next.handle(req); // want this one to return always
      });
      // below is cos the app won't compile and it returns immediately
      return next.handle(req);
    }
  }
  </code></pre>