6: Get Data from a Server
[examples/angular-tour-of-heroes] / src / app / hero-search / hero-search.component.ts
1 import { Component, OnInit } from '@angular/core';
2
3 import { Observable, Subject } from 'rxjs';
4
5 import {
6   debounceTime, distinctUntilChanged, switchMap
7 } from 'rxjs/operators';
8
9 import { Hero } from '../hero';
10 import { HeroService } from '../hero.service';
11
12 @Component({
13   selector: 'app-hero-search',
14   templateUrl: './hero-search.component.html',
15   styleUrls: [ './hero-search.component.css' ]
16 })
17 export class HeroSearchComponent implements OnInit {
18   heroes$: Observable<Hero[]>;
19   private searchTerms = new Subject<string>();
20
21   constructor(private heroService: HeroService) {}
22
23   // Push a search term into the observable stream.
24   search(term: string): void {
25     this.searchTerms.next(term);
26   }
27
28   ngOnInit(): void {
29     this.heroes$ = this.searchTerms.pipe(
30       // wait 300ms after each keystroke before considering the term
31       debounceTime(300),
32
33       // ignore new term if same as previous term
34       distinctUntilChanged(),
35
36       // switch to new search observable each time the term changes
37       switchMap((term: string) => this.heroService.searchHeroes(term)),
38     );
39   }
40 }