为什么rxjs没有取消我的承诺

Why is rxjs not canceling my promise?

本文关键字:我的 承诺 取消 rxjs 为什么      更新时间:2023-09-26

我在我的angular应用程序中使用rxjs。当进行多个REST调用时,我并不总是按照我想要的顺序获得数据。

控制器:

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});
},

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

既然您没有做任何事情来"链接"这两个序列,那么RxJs如何知道它们是相关的呢?

你需要创建一个单独的流,然后你可以使用switch只观察最近的请求:

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来取消正在进行的请求。