1

I have an input with a material autocomplete component linked to it. as the user types calls are made to the server for results. its working fine as the server returns the results in order (for now) But I still would like to cancel the last call before triggering the next one. this is the method I'm using now:

    getCodigosPon(needle: string): Observable<any> {
      if (needle.length > 3) {
        const options = createRequestOption({ idPon: needle });
        return this.http.get<string[]>(this.codigoPonUrl, { params: options, observe: 'response' });
      } else {
        return of([]);
      }
    }
1

1 Answer 1

4

Here is usual set up for input to HTTP connection.

  • debounceTime is optional, yet nice to have.
  • switchMap is essential, it makes it so, that the previous request will be cancelled
class MyComponent {
  readonly input$ = new BehaviourSubject('default input value');

  // ...

  readonly codigosPonValue$ = this.input$.pipe(
    debounceTime(300), // If you want...
    switchMap(needle => {
      if (needle.length > 3) {
        const params = createRequestOption({ idPon: needle });
        return this.http.get<string[]>(this.codigoPonUrl, { params });
      } else {
        return of([]);
      }
    })
  );
}

With HTML like so...

<input (change)="input$.next($event.value)>
<pre>
{{codigosPonValue$ | async | json}}
</pre>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.