如预期Rxjs操作withLatestFrom不起作用

问题描述 投票:0回答:2

我有一个可观察userInput$返回每N秒时用户键入的数据流来输入。我想收到最新的输入和传递作为参数传递给函数service.search(x)将返回另一个观察到的数据的列表。

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

任何为什么我的代码不能正常工作?

userInput$返回stringthis.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]

angular rxjs
2个回答
0
投票

你已经从管道$ userInput到withLatestFrom输出,但认购依然不知道什么提供作为输出。在这里,你需要映射你的输出。

尝试这个。

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));

0
投票

两种意见:

首先,您实际上并不管道传输到map除非你的代码示例是一个错字,应该喜欢这个:

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

第二,withLatestFrom旨在提供由所提供的可观察到的(一个或多个)发出的最新的值(一个或多个)未接收,并从上游观察到的,其更类似于switchMap变化作出反应。考虑这个:

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

请注意,这个假设this.service.search返回Observable响应。如果没有,你需要每from的实际返回类型ofsearch包。

© www.soinside.com 2019 - 2024. All rights reserved.