Search with mergeMap
A case for MergeMap:
Let's say we wanted to implement an AJAX search feature in which every keypress in a text field will automatically perform a search and update the page with the results. How would this look? Well we would have an Observable subscribed to events coming from an input field, and on every change of input we want to perform some HTTP request, which is also an Observable we subscribe to. What we end up with is an Observable of an Observable.
By using mergeMap we can transform our event stream (the keypress events on the text field) into our response stream (the search results from the HTTP request).
app/services/search.service.ts
1
import {HttpClient} from '@angular/http';
2
import {Injectable} from '@angular/core';
3
import {map} from 'rxjs/operators';
4
5
@Injectable()
6
export class SearchService {
7
8
constructor(private http: HttpClient) {}
9
10
search(term: string) {
11
return this.http
12
.get('https://api.spotify.com/v1/search?q=' + term + '&type=artist')
13
.pipe(map((response) => response.json()))
14
15
}
16
}
Copied!
Here we have a basic service that will undergo a search query to Spotify by performing a get request with a supplied search term. This search function returns an Observable that has had some basic post-processing done (turning the response into a JSON object).
OK, let's take a look at the component that will be using this service.
app/app.component.ts
1
import { Component } from '@angular/core';
2
import { FormControl, FormGroup, FormBuilder } from '@angular/forms';
3
import { SearchService } from './services/search.service';
4
import { map } from 'rxjs/operators';
5
import { Artist } from './types/artist.type';
6
7
@Component({
8
selector: 'app-root',
9
template: `
10
<form [formGroup]="coolForm"><input formControlName="search" placeholder="Search Spotify artist"></form>
11
12
<div *ngFor="let artist of artists$ | async">
13
{{artist.name}}
14
</div>
15
`
16
})
17
18
export class AppComponent {
19
searchField: FormControl;
20
coolForm: FormGroup;
21
artists$: Observable<Artist[]>;
22
23
constructor(private searchService:SearchService, private fb:FormBuilder) {
24
this.searchField = new FormControl();
25
this.coolForm = fb.group({search: this.searchField});
26
27
this.artists$ = this.searchField.valueChanges.pipe(
28
debounceTime(400),
29
mergeMap(term => this.searchService.search(term)),
30
map(result => result.artist.items)
31
);
32
}
33
}
Copied!
Here we have set up a basic form with a single field, search, which we access through an observable. We've also set up a simple binding for any artists coming from the SearchService. The real magic here is mergeMap which allows us to flatten our two separate subscribed Observables into a single cohesive stream we can use to control events coming from user input and from server responses.
Note that mergeMap flattens a stream of Observables (i.e Observable of Observables) to a stream of emitted values (a simple Observable), by emitting on the "trunk" stream everything that will be emitted on "branch" streams.
Last modified 3mo ago
Copy link