角度:文本搜索 rxjs 问题



我正在Angular 6中创建搜索。我的直播遇到了困难。

我希望我的 rx 流:

  1. 接受文本输入更改
  2. 与一个subject结合使用,该告诉流在单击按钮时获得更多结果(增量限制(
  3. 调用服务

我所拥有的工作,除了:

  1. 当主题发出时,它什么都不做,我希望switchmap启动,从而得到服务器响应。
  2. 如何在每次发出subject时增加限制 10?

    searchInput: FormControl = new FormControl();
    showMore$: Subject<number> = new Subject();
    ngOnInit() {
    this.searchInput
    .valueChanges
    .pipe(
    debounceTime(300),
    distinctUntilChanged(),
    withLatestFrom(this.showMore$.pipe(startWith(10), tap(val => {
    //how to increment the value here?
    }))),
    //switchmap not called when showMore$ emits...
    switchMap(([searchTerm, limit]) => {
    return this.myservice.search(searchTerm, limit)
    }),
    )
    .subscribe(response => {
    this.results = response;
    });
    }
    showMore(): void {
    this.showMore$.next(10);
    }
    

据我所知,switchMap 应该按原样工作,尽管您可能希望在其中进行一些错误处理。

要将值增加 10,只需将该值放入存储中并触发一个操作,该操作将触发化简器将其增加 10 以进行下一次轮次。

.pipe(
debounceTime(300),
distinctUntilChanged(),
// get the value from the store using an ngrx selector
withLatestFrom(this.store.pipe(select(selectValue))),
switchMap(([searchTerm, limit]) => {
// essential to catchError else an HTTP error response will disable this
return this.myservice.search(searchTerm, limit).pipe(
catchError(() => {
return of('an error string which will be passed down the pipe on an error')
})
)
}),
tap(() => this.store.dispatch(new IncrementValueByTenAction()))
)

此外,使用大量 tap 语句来记录沿管道传递的值。

最新更新