【问题标题】:Angular & RxJS5 - updating data from http & socketAngular & RxJS5 - 从 http & socket 更新数据
【发布时间】:2017-03-10 16:55:37
【问题描述】:

我有一个场景需要:

  1. 获取路由参数
  2. 使用路由参数调用http服务
  3. 一旦 http 响应,使用相同的路由参数调用套接字服务
  4. 每次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;
    }

【问题讨论】:

    标签: angular rxjs5


    【解决方案1】:

    根据我对您的流程的理解,我不需要您需要任何 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
                        )
                    );
    

    【讨论】:

    • 我没有意识到嵌套运算符是合法的?我的印象是它会引起问题,但似乎不是。谢谢
    猜你喜欢
    • 2020-08-07
    • 2014-09-19
    • 2018-06-12
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 2017-06-11
    相关资源
    最近更新 更多