title: Angular|RxJS - Type-ahead search request gets cancelled by browser (on click)
body: <p>I am new to RxJS (and frontend) but I know that <code>switchMap()</code> in the following code is used to break and re-run a search request as the user types into a text box. Search works fine, the only problem is that if the user clicks anywhere outside the textbox (like anywhere on the page, or on a different browser tab or window, or chrome devtools) after entering the text and before the request is fulfilled, the browser cancels the search request altogether.</p>
  <p>(Note: The search request is cancelled and re-run correctly if user keeps typing while the request is being processed. Only click event causes the complete request cancellation without re-run)</p>
  <p><a href="https://i.stack.imgur.com/6JjuW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6JjuW.png" alt="enter image description here" /></a></p>
  <pre class="lang-js prettyprint-override"><code>  search = (input: Observable&lt;string&gt;) =&gt; {
      return input.pipe(
        debounceTime(500),
        distinctUntilChanged(),
        switchMap((text) =&gt; text.length &lt; 2 ? this.clearDropDown() // clear dropdown showing list of item names.
          : this.onKeyUp(text).pipe(
            map(result =&gt; {
             this.spinnerService.end(); // stop loading spinner.
            if (results.data) {
                return results.data; // return list of item names for the dropdown.
            }
        })
          )));
    }
  
    onKeyUp(text: string): Observable&lt;any&gt; {
        this.spinnerService.start(); // start loading spinner animation overlay on the page.
        return this.http.post(this.apiUrlString, { 'itemName': text }); // this search request works fine.
    }
  </code></pre>
  <p>The HTML, in case it is relevant:</p>
  <pre class="lang-html prettyprint-override"><code>    &lt;div&gt;
        &lt;input
          id=&quot;itemSearchValue&quot;
          type=&quot;text&quot;
          class=&quot;form-control/bg-light/rounded/dropdown-toggle&quot;
          [(ngModel)]=&quot;selectedItem&quot;
          (selectItem)=&quot;onSelectItem($event)&quot; // irrelevant to the question.
          formControlName=&quot;itemSearchValue&quot;
          [ngbTypeahead]=&quot;search&quot;
          #instance=&quot;ngbTypeahead&quot; /&gt;
      &lt;/div&gt;
  </code></pre>
  <p>How can I make sure the request is not cancelled by the browser when the user emits clicks somewhere? I'd like to keep the <code>switchMap()</code> method.</p>