Ben*_*ros 2 javascript reactive-programming rxjs rxjs5 angular
我有一个自动完成输入,当用户输入时,它从多个端点获取数据,例如:
//service call to fetch data and return as single observable
getAutocompleteSuggestions() {
const subs$ = [
this.http.get(endpoint1),
this.http.get(endpoint2),
this.http.get(endpoint3)
];
return Observable.forkJoin(...subs$);
}
Run Code Online (Sandbox Code Playgroud)
这些端点中的每一个都返回以下形式的数据:
{ data: [], status: xyz }
Run Code Online (Sandbox Code Playgroud)
我想使用 switchmap,因为我只想显示最终调用的结果,并尝试了以下操作:
this.getAutocompleteSuggestions(query)
.switchMap(res => {
return res.data;
})
.subscribe((results: any) => {
this.results = results;
});
Run Code Online (Sandbox Code Playgroud)
但是 switchmap 中的“res”是一个数组,知道结果如何包含一个包含来自任意数量可观察对象响应数据的单个数组吗?
我不完全明白你想要什么,但我认为就是这样:
$filter: Subject<string> = new Subject(); //I guess we have some value to filter by??
Run Code Online (Sandbox Code Playgroud)
向主题推送一个值:
this.$filter.next(myNewValue);
Run Code Online (Sandbox Code Playgroud)
在构造函数或 init 中:
this.$filter
.switchMap(filterValue => { //Get the values when filter changes
subs$ = [
this.http.get(endpoint1 + filterValue),
this.http.get(endpoint2 + filterValue),
this.http.get(endpoint3 + filterValue)
];
return Observable.forkJoin(...subs$);
})
.map(results => { //now map you array which contains the results
let finalResult = [];
results.forEach(result => {
finalResult = finalResult.concat(result.data)
})
return final;
})
.subscribe(); //Do with it what you want
Run Code Online (Sandbox Code Playgroud)
当我们将新值放入我们的主题时,整个蒸汽将再次执行。SwitchMap 将取消所有准备好的请求(如果有)。