Last active
July 9, 2019 09:14
-
-
Save bernardo-cs/60d841ff3d363d32f9fa752868bc49a4 to your computer and use it in GitHub Desktop.
Angular component that fully consumes a paginated API recursivly with RxJS expand operator. Example live on: https://stackblitz.com/edit/angular-yja4k7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } from '@angular/core'; | |
import { combineLatest, Subject, of, empty, Observable } from 'rxjs'; | |
import { map, tap, expand } from 'rxjs/operators'; | |
@Component({ | |
selector: 'my-app', | |
template: ` | |
<input type="text" (input)="term$.next($event.target.value)" /> | |
<div *ngIf="users$ | async as users"> | |
<span> {{ users | json }} </span> | |
</div> | |
`, | |
styleUrls: ['./app.component.css'] | |
}) | |
export class AppComponent { | |
term$: Subject<string> = new Subject(); | |
users$: Observable<Array<{id: number, name: string}>> = this.term$.asObservable().pipe( | |
map(t => ({ term: t, index: 0, result: [] })), | |
expand(t => { | |
if (t.index > 3) { | |
return empty(); | |
} | |
return fakeEndpoint(t.index, t.term).pipe( | |
map(res => { | |
return { | |
term: t.term, | |
index: t.index + 1, | |
result: t.result.concat(res) | |
}; | |
}) | |
); | |
}), | |
map(res => res.result) | |
); | |
} | |
const fakeNames = ['Eduard', 'Paula', 'Nick', 'Sara']; | |
function fakeEndpoint(index: number, term: string) { | |
return of([{ id: index, name: `${fakeNames[index]} ${term}` }]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment