1 import { Component, OnInit } from '@angular/core';
3 import { Observable, Subject } from 'rxjs';
6 debounceTime, distinctUntilChanged, switchMap
7 } from 'rxjs/operators';
9 import { Hero } from '../hero';
10 import { HeroService } from '../hero.service';
13 selector: 'app-hero-search',
14 templateUrl: './hero-search.component.html',
15 styleUrls: [ './hero-search.component.css' ]
17 export class HeroSearchComponent implements OnInit {
18 heroes$: Observable<Hero[]>;
19 private searchTerms = new Subject<string>();
21 constructor(private heroService: HeroService) {}
23 // Push a search term into the observable stream.
24 search(term: string): void {
25 this.searchTerms.next(term);
29 this.heroes$ = this.searchTerms.pipe(
30 // wait 300ms after each keystroke before considering the term
33 // ignore new term if same as previous term
34 distinctUntilChanged(),
36 // switch to new search observable each time the term changes
37 switchMap((term: string) => this.heroService.searchHeroes(term)),