为什么 rxjs 不取消我的承诺?

Why is rxjs not canceling my promise?

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

既然你没有对这两个序列做任何事情"link",那么 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 用于取消正在进行的请求。