add Edit the HeroSearchComponent class
This commit is contained in:
parent
644139b42c
commit
ef2309f0f1
|
@ -1,11 +1,40 @@
|
|||
import { Component } from '@angular/core';
|
||||
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',
|
||||
imports: [],
|
||||
templateUrl: './hero-search.component.html',
|
||||
styleUrl: './hero-search.component.css'
|
||||
styleUrls: [ './hero-search.component.css' ]
|
||||
})
|
||||
export class HeroSearch {
|
||||
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)),
|
||||
);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue