【发布时间】:2019-06-06 06:19:40
【问题描述】:
我使用主题和 async 管道发出 http 请求并根据搜索词进行搜索。我使用角度教程来执行此操作,该教程使用 switchmap 运算符和 keyup 方法的一些延迟时间。
击键工作正常,但我第一次想发出请求调用并显示列表,然后用户可以根据需要进行搜索。
但在调用 next 时,switchmap 运算符不会触发!
搜索输入:
<input type="text" placeholder="Search name" [(ngModel)]="searchTerm" (keyup)="callSearch()">
打字稿代码:
products$: Observable<ProdSearch[]>;
searchProducts$ = new Subject<string>();
callSearch() {
if (this.searchTerm.length > 0 ){
this.searchProducts$.next(this.searchTerm);
}
}
订阅:
this.products$ = this.searchProducts$.pipe(
debounceTime(1000),
distinctUntilChanged(),
switchMap(term => {
const options: PagingOptions = {};
options.limit = "5";
if (term.length !== 0) {
options.filterOptions = "name_search_" + this.searchTerm;
}
return this.service.getCollection<ProdSearch>(this.baseUrl + 'products/search', options)
.pipe(map(collection => collection.records))
})
我想第一次使用按钮运行 switchmap,但它不起作用,它只适用于击键。
showLastProducts() {
this.showChangeList = true;
this.searchProducts$.next(''); // The switchmap won't work
}
【问题讨论】:
-
尝试使用
BehaviorSubject而不是Subject,或使用startWith运算符。问题是主题不会发出第一个值,因此您必须手动完成,或者使用他们的小兄弟,即行为一。 -
... 或添加
startWith运算符
标签: angular rxjs angular6 observable angular7