title: How to use RxJS to cancel previous HTTP Requests in an Angular Service
body: <p>I know there are lots of questions like this but they have often confused me or have been difficult for me to apply to my situation, so I am asking here so I can get it round my head. In my component typescript file I have a method that calls a service that returns api data using http, so when a user clicks a chip on the interface they call the following..</p>
  <pre><code>fetchCounts(filters?: any): void {
      this.loaded = false;
      this.apiCall = this.api.getCounts(filters).subscribe((results: any) =&gt; {
          // do something with the returned data
          this.loaded = true;
          this.apiCall.unsunscribe()
      });
  }
  </code></pre>
  <p>My api service looks like this:</p>
  <pre><code>getCounts(filters?: any): Observable&lt;any&gt; {
      let params: any;
      if (filters?.car?.length || filters?.bike?.length) {
        params = this.addObjectToParams(new HttpParams(), filters);
      }
      return this.http.get('api/counts', { params } )
        .pipe(map(this.extractData));
  }
  </code></pre>
  <p>Now I have noticed when a user clicks my interface adding and removing chips that make an API call the interface seems to no longer show the true data due to the overload/large amounts of API calls. So I want to cancel the current api/http call if a new one is made (if <code>fetchCounts</code> is called again). I have tried adding a debounce to the .pipe in the <code>getCounts</code>method like so... <code>.pipe( debounceTime(500), map(this.extractData));</code> but it doesn't seem to do anything. I think I have to add a <code>switchMap</code> but when I add my code it just breaks due to a lack of understanding on my part. I am currently looking through the docs... but any help would be appreciated.</p>