为什么rxjs没有取消我的承诺? [英] Why is rxjs not canceling my promise?

查看:185
本文介绍了为什么rxjs没有取消我的承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 angular 应用中使用 rxjs 。当多个 REST 调用时,我并不总是以我想要的顺序返回数据。

I am using rxjs in my angular app. I don't always get the data back in the order I want when multiple REST calls are made.

控制器:

constructor() {
    rx.Observable.fromPromise(this.getExpenses(toDate, fromDate))).subscribe(res => {
            that.setExpenses(res);
    }); 
}

getExpenses(toDate, fromDate) {
    return this.expenseService.getExpenses(fromDate, toDate);   
}

updateDate() {
    rx.Observable.fromPromise(this.getExpenses(toDate, fromDate))).subscribe(res => {
            that.setExpenses(res);
    });     
}

服务:

getExpenses: function(fromDate, toDateloadExtendedData) {
    return Restangular.all('expenses').getList({fromDate: fromDate, toDate: toDate});
},

在我的构造函数中,我想获得当年的结果,但有时用户会在构造函数中返回之前更新日期。然后我有一个竞争条件,因为用户想要 updateDate info,而不是构造函数 info。如何取回最近请求的数据?

In my constructor, I want to get the results for the current year, but sometimes the user will update the date before the call in the constructor returns. I then have a race condition, because the user wants the updateDate info, not the constructor info. How do I get back the most recently requested data?

推荐答案

由于您没有做任何链接这两个序列, RxJs能否知道它们是相关的?

Since you have done nothing to "link" the two sequences, how can RxJs ever know they are related?

您需要创建一个流,然后您可以使用切换仅观察最近的请求:

You need to create a single stream, then you can use switch to observe the most recent request only:

constructor() {
    this._requests = new Rx.Subject();

    // listen to requests
    this._requests.switch().subscribe(res => this.setExpenses(res));

    // start the first request
    this._requests.onNext(this.getExpenses(toDate, fromDate));
}

updateDate() {
    // start a new request
    this._requests.onNext(this.getExpenses(toDate, fromDate));
}

请注意,这实际上不会取消以前的要求。它会忽略它们产生的任何结果。如果您确实要取消它们,您的费用服务需要提供一个API来取消正在进行的请求。

Note that this won't actually cancel the previous requests. It will just ignore any results they produce. If you really want to cancel them, your expense service would need to provide an API for cancelling in-progress requests.

这篇关于为什么rxjs没有取消我的承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆