在 Angular 教程从服务器获取数据 ( https://angular.io/tutorial/toh-pt6 ) 中,有一个代码片段用于处理搜索,并进行 http 调用以获取带有搜索词的英雄。
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)),
);
}
}
假设我添加了另一个按钮来按名称对英雄进行排序,它由 sort
方法处理
sort(order: 'asc' | 'desc') {
this.sortingOrder$.next(order);
}
举两种不同的情况
情况1:点击排序时,获取当前searchTerm和sortOrder的英雄 this.heroService.searchHeroes(term, sortOrder)
并将其应用到heroes$
流。
情况2:点击排序时,清空searchTerm,仅按sortOrder获取英雄,例如: this.heroService.searchHeroes('', sortOrder)
并将其应用到 heroes$
流。这意味着在这种情况下排序按钮和搜索是独立工作的。
对于这些情况,我应该如何更新 heroes$
流?
最佳答案
您可以通过使用 combineLatest
来实现此目的运算符并添加两个可观察量来创建流。它接收一系列可观察的源,一旦所有源至少发出一次,映射值的数组就可供使用。请注意,只有当两个源都发出至少一个值时,combineLatest
才会发出。一个BehaviorSubject
在这里通常很有用,因为它在创建时与 Subject
相对应,会发出一个值。
关于javascript - Angular Rxjs : How to handle multiple events that affects a base observable stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73749618/