【问题标题】:Angular: Text search rxjs issueAngular:文本搜索 rxjs 问题
【发布时间】:2019-02-10 23:53:07
【问题描述】:

我正在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);
    }
    

【问题讨论】:

    标签: angular rxjs6


    【解决方案1】:

    据我所知,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 语句来记录通过管道传递的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-14
      • 2011-01-28
      相关资源
      最近更新 更多