我有一个可观察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到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));
两种意见:
首先,您实际上并不管道传输到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
的实际返回类型of
或search
包。