62
Auto-complete with Angular material and RxJS
This article talks about an efficient way to implement auto-complete feature using Angular concepts. The key components used in this demonstration are as follows:
Let us now see how we go about it:
The action

Every time a new value is emitted into the action stream, it returns an observable from the http

So why
BehaviorSubject
starts with an empty string. The action$
is an observable
built out of this subject.Every time a new value is emitted into the action stream, it returns an observable from the http
GET
request. Since this is a higher-order observable (i.e., an observable returning an observable), we make use of one of the higher order functions like switchMap
.So why
switchMap
(and not other higher order functions like concatMap
or mergeMap
)? The reason is: switchMap
unsubscribes from the previous observable once a new value is emitted by the parent observable.What this means is - as soon as the user types in another letter or removes a letter, there is simply no need to subscribe and execute the rest call for the previous values. The user is only interested to see the results of the search according to his/her current input. And
switchMap
does this automatically, and thus gets rid of unwanted rest calls.We can also get additional control on when to fire the rest service depending on the length of the user's input. For example, in this demo, I fire the rest call only when the user has entered at least 2 characters. If not, then I return an observable of empty array (using
of([])
).Cheers!
62