简体   繁体   English

Angular和RxJS5-从http和套接字更新数据

[英]Angular & RxJS5 - updating data from http & socket

I have a scenario where I need to: 我有一种情况需要:

  1. Get route params 获取路线参数
  2. Use route params to call http service 使用路由参数调用http服务
  3. Once http responds, use same route params to call a socket service http响应后,使用相同的路由参数调用套接字服务
  4. Each time socket responds, update data from http service 每次套接字响应时,从http服务更新数据

Ideally I would like to keep this in a stream. 理想情况下,我想保持此状态。

If only I could use CombineLatest ? 如果我可以使用CombineLatest or involve the Scan operator? 或涉及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;
    }

From how I understood your flow I don't need you need any of the combineLatest or scan operators, you just need to nest two switchMaps : 根据我对流程的了解,我不需要任何combineLatestscan运算符,只需要嵌套两个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
                    )
                );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM