Skip to content

Instantly share code, notes, and snippets.

@LayZeeDK
Created December 4, 2018 06:57
Show Gist options
  • Save LayZeeDK/0c9a39993a377a30e2713a51140475c4 to your computer and use it in GitHub Desktop.
Save LayZeeDK/0c9a39993a377a30e2713a51140475c4 to your computer and use it in GitHub Desktop.
Hero search: Mixed component model
import { Component, OnInit } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';
@Component({
selector: 'app-hero-search',
templateUrl: './hero-search.component.html',
styleUrls: [ './hero-search.component.css' ]
})
export class HeroSearchComponent implements OnInit {
heroes$: Observable<Hero[]>;
private searchTerms = new Subject<string>();
constructor(private heroService: HeroService) {}
// Push a search term into the observable stream.
search(term: string): void {
this.searchTerms.next(term);
}
ngOnInit(): void {
this.heroes$ = this.searchTerms.pipe(
// wait 300ms after each keystroke before considering the term
debounceTime(300),
// ignore new term if same as previous term
distinctUntilChanged(),
// switch to new search observable each time the term changes
switchMap((term: string) => this.heroService.searchHeroes(term)),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment