Skip to content

Instantly share code, notes, and snippets.

@bernardo-cs
Last active July 9, 2019 09:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bernardo-cs/60d841ff3d363d32f9fa752868bc49a4 to your computer and use it in GitHub Desktop.
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
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