Learn RxJS
Search…
Type Ahead
By adamlubek
This recipe demonstrates the creation of type ahead client side code.

Example Code

Typeahead
1
// RxJS v6+
2
import { fromEvent, of } from 'rxjs';
3
import {
4
debounceTime,
5
distinctUntilChanged,
6
map,
7
switchMap,
8
tap
9
} from 'rxjs/operators';
10
11
const getContinents = keys =>
12
[
13
'africa',
14
'antarctica',
15
'asia',
16
'australia',
17
'europe',
18
'north america',
19
'south america'
20
].filter(e => e.indexOf(keys.toLowerCase()) > -1);
21
22
const fakeContinentsRequest = keys =>
23
of(getContinents(keys)).pipe(
24
tap(_ => console.log(`API CALL at ${new Date()}`))
25
);
26
27
fromEvent(document.getElementById('type-ahead'), 'keyup')
28
.pipe(
29
debounceTime(200),
30
map((e: any) => e.target.value),
31
distinctUntilChanged(),
32
switchMap(fakeContinentsRequest),
33
tap(c => (document.getElementById('output').innerText = c.join('\n')))
34
)
35
.subscribe();
Copied!

html

1
Get continents
2
<input id="type-ahead" />
3
<hr />
4
<div id="output"></div>
Copied!

Operators Used

Last modified 1yr ago