heroes$: Observable<Hero[]>;
// 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(500),
// ignore new term if same as previous term
distinctUntilChanged(),
// switch to new search observable each time the term changes
switchMap((term: string) => this.searchService.searchHeroes(term)),
);
}
onClear(event){
console.log('clear observable');
//clear array
// I have Tried these two things to clear observable array but it not..
this.heroes$.map(Hero => Hero = []);
Observable.of<Hero[]>([]);
}
我有一个搜索建议的Searh框具有可观察的数组..在onClear事件期间,Observable数组应该为空。
答案 0 :(得分:1)
您可以尝试类似
的内容this.heroes$ = this.searchTerms.pipe(
// wait 300ms after each keystroke before considering the term
debounceTime(500),
// ignore new term if same as previous term
distinctUntilChanged(),
// switch to new search observable each time the term changes
switchMap((term: string) => {
if (term === '') return Observable.of<Hero[]>([]);
else return this.searchService.searchHeroes(term);
}),
);
(如果this.heroes$
发出[]
,this.searchTerms
会发出''