在RXJS中结合两个ajax响应

时间:2016-06-11 21:30:53

标签: javascript rxjs rxjs5

我还在学习RXJS(刚刚开始),我知道我的问题是初学者。我试图结合外部呼叫的两个响应。假设我调用call1和call2,我应该能够订阅一个组合响应。

以下是我的代码

var arrayWeather =['http://apidev.accuweather.com/currentconditions/v1/250111.json?language=en&apikey=hoArfRosT1215', 'http://apidev.accuweather.com/currentconditions/v1/4-204108_1_AL.json?language=en&apikey=hoArfRosT1215'];
var refreshClickStream = Rx.Observable.fromEvent(document.querySelector('.refresh'), 'click');

refreshClickStream.subscribe(function(e){
  Rx.Observable.fromArray(arrayWeather)
    .flatMap(function(datathings){ 
        return Rx.DOM.Request.get(datathings)
    })
    .subscribe(function(data){
        console.log(data.response);
    });
});

1 个答案:

答案 0 :(得分:1)

您需要Zip

var combined = Rx.Observable.zip(refreshClickStream, anotherStream);

然后订阅合并

var subscription = combined.subscribe(
  function (x) {
  },
  function (err) {
  },
  function () {
  });

您还可以在Zip中添加一个函数,您可以在其中告诉zip操作如何将两者结合起来

var combined = Rx.Observable.zip(refreshClickStream, anotherStream, function (firstStreamItem, secondStreamItem) {
    return { first: firstStreamItem, second: secondStreamItem };
  });

有关RxJS Zip的更多信息,请see here