【问题标题】:Rxjs operator withLatestFrom does not work as expectedRxjs 运算符 withLatestFrom 无法按预期工作
【发布时间】:2019-02-04 08:30:45
【问题描述】:

我有一个可观察的userInput$,当用户键入要输入时,它每 N 秒返回一次数据流。我想接收最新的输入并将其作为参数传递给函数service.search(x),该函数将返回另一个带有数据列表的可观察对象。

this.userInput$
  .pipe(withLatestFrom(x => this.service.search(x)))
  .subscribe(x => {
    //do not receiving any data here
  });

为什么我的代码不起作用?

我的userInput$ 返回一个string 我的this.service.search(x) 返回一个数组——这就是我想要得到的结果。

更新:

const example = this.userInput$
  .pipe(withLatestFrom(x => this.service.search(x)),
  map(([userInput, searchOutput ]) => { // error here
    return {query: userInput, result: searchOutput};
  })
);

[userInput, searchOutput] - 收到错误[ts] Type 'Observable<GetSearch[]>' is not an array type. [2461]

仅用于测试将this.service.search(x) 更改为of(x)

const example = this.userInput$
  .pipe(withLatestFrom(x => of(x)),
  map(([userInput, searchOutput ]) => { // error here
    return {query: userInput, result: searchOutput};
  })
);

map 返回错误[ts] Type 'Observable<any>' is not an array type. [2461]

【问题讨论】:

  • userInput$ 返回什么? & search(x) 返回什么?您对订阅有何期待?

标签: angular rxjs


【解决方案1】:

两个观察结果:

首先,除非您的代码示例是拼写错误,否则您实际上并没有通过管道发送到map,它应该是这样的:

const example = this.userInput$.pipe(
  withLatestFrom(x => this.service.search(x)),
  map(([userInput, searchOutput ]) => {
    return {query: userInput, result: searchOutput};
  })
);

其次,withLatestFrom 旨在提供由所提供的 observable 发出的最新值,而不是接收和响应上游 observable 的变化,这更类似于switchMap。请考虑一下:

const example = this.userInput$.pipe(
  switchMap(x => this.service.search(x).pipe(
    map(searchOutput => {
      return {query: x, result: searchOutput};
    })
  )),
);

请注意,这假定this.service.search 返回Observable 响应。如果没有,则需要根据search 的实际返回类型使用fromof 进行包装。

【讨论】:

    【解决方案2】:

    您已将 userInput$ 的输出通过管道传输到 withLatestFrom,但 subscribe 仍然不知道要提供什么作为输出。在这里,您需要映射您的输出。

    试试这个。

    const example = this.userInput$
      .pipe(withLatestFrom(x => this.service.search(x)),
      map(([userInput, searchOutput ]) => {
        return {query: userInput, result: searchOutput};
      })
    );
    const subscribe = example.subscribe(val => console.log(val.result));
    

    【讨论】:

    • 在地图功能[userInput, searchOutput ] - 得到一个错误[ts] Type 'Observable<GetSearch[]>' is not an array type. [2461]。查看更新后的问题。
    • 你能分享一下 userInput observable 是如何传输值的吗?
    • 对此的任何解决方案,我在尝试实现 withLatestFrommap 时遇到了类似的问题。 ` Type 'Observable' 必须有一个返回迭代器的 '[Symbol.iterator]()' 方法。`
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 2019-09-23
    • 2020-01-13
    • 2021-08-07
    • 1970-01-01
    • 2015-05-11
    • 2019-06-20
    相关资源
    最近更新 更多