Angular & RxJS5 - 从 http & socket 更新数据
Angular & RxJS5 - updating data from http & socket
我有一个场景需要:
- 获取路由参数
- 使用路由参数调用http服务
- http 响应后,使用相同的路由参数调用套接字服务
- 每次socket响应,从http服务更新数据
理想情况下,我想将其保留在流中。
如果我可以使用 CombineLatest
就好了?或涉及 Scan
运算符?
this.data$ = this.route.params
.switchMap(params => {
return Observable.forkJoin([
Observable.of(params),
this.http.get('api', { prop1: params.prop1, prop2: params.prop2 })
])
}).combineLatest(([params, data]) => {
this.socket.get('event', { prop1: params.prop1, prop2: params.prop2 }),
updateData
})
private updateData(data, socketData): any[] {
//only returns data = [params, data]
//socketData always undef
return data;
}
根据我对你流程的理解,我不需要你需要任何 combineLatest
或 scan
运算符,你只需要嵌套两个 switchMaps
:
this.data$ = this.route.params
.switchMap(params => this.http.get('api', { prop1: params.prop1, prop2: params.prop2 })
.switchMap(httpResult => this.socket.get('event', { prop1: params.prop1, prop2: params.prop2 }) // assuming socket.get(...) is a perpetual stream
.map(socketResult => doWhateverCombinationWith(httpResult, socketResult))
.startWith(httpResult); // not sure if this is required, your question is kind of vague, but essentially this will cause the stream to emit the original httpResult before there is socketData
)
);
我有一个场景需要:
- 获取路由参数
- 使用路由参数调用http服务
- http 响应后,使用相同的路由参数调用套接字服务
- 每次socket响应,从http服务更新数据
理想情况下,我想将其保留在流中。
如果我可以使用 CombineLatest
就好了?或涉及 Scan
运算符?
this.data$ = this.route.params
.switchMap(params => {
return Observable.forkJoin([
Observable.of(params),
this.http.get('api', { prop1: params.prop1, prop2: params.prop2 })
])
}).combineLatest(([params, data]) => {
this.socket.get('event', { prop1: params.prop1, prop2: params.prop2 }),
updateData
})
private updateData(data, socketData): any[] {
//only returns data = [params, data]
//socketData always undef
return data;
}
根据我对你流程的理解,我不需要你需要任何 combineLatest
或 scan
运算符,你只需要嵌套两个 switchMaps
:
this.data$ = this.route.params
.switchMap(params => this.http.get('api', { prop1: params.prop1, prop2: params.prop2 })
.switchMap(httpResult => this.socket.get('event', { prop1: params.prop1, prop2: params.prop2 }) // assuming socket.get(...) is a perpetual stream
.map(socketResult => doWhateverCombinationWith(httpResult, socketResult))
.startWith(httpResult); // not sure if this is required, your question is kind of vague, but essentially this will cause the stream to emit the original httpResult before there is socketData
)
);