我正在使用angular.js。我有一个具有可观察和间隔的服务。我需要服务或控制器中的其他功能来在动作发生时停止此可观察。
我的服务代码:
'use strict';
import assert from 'assert';
import * as rx from 'rxjs';
export class RTDBService {
constructor($http, rtdbSettings) {
'ngInject';
this.$http = $http;
this.rtdbSettings = rtdbSettings;
}
observable(asset, interval = 5000, tags) {
assert(asset, 'Asset parameter not provided');
const path = `${this.rtdbSettings.root}/${asset}`;
return rx.Observable.interval(interval)
.concatMap(() => this.$http.get(path))
.map((res) => res);
}
}
我的组件控制器代码:
'use strict';
import Dygraph from 'dygraphs';
import dataViewTemplate from './data-view.component.html';
class DataViewController {
constructor($scope, rtdb, $window) {
'ngInject';
this.$scope = $scope;
this.$window = $window;
this.rtdb = rtdb;
}
$onInit(){
const interval = parseInt(this.interval);
this.$scope.tags = (this.tags).split(',');
this.$scope.data = this.rtdb.observable(this.asset, interval, this.$scope.tags).do(() => null, (err) => {
this.$scope.dataStatus = this.getStatus(err.status);
}).map(this.transformData.bind(this));
}
transformData(data) {
// no important code
}
getStatus(status)
{
// no important code
}
}
export const DataViewComponent = {
controller: DataViewController,
template: dataViewTemplate,
bindings: {
asset: '<',
interval: '<',
tags: '<'
}
};
答案 0 :(得分:1)
正如@Pace在评论中提到的:你想要的是takeUntil()
:
$onInit(){
const interval = parseInt(this.interval);
this.$scope.tags = (this.tags).split(',');
this.$scope.data = this.rtdb.observable(this.asset, interval, this.$scope.tags).do(() => null, (err) => {
this.$scope.dataStatus = this.getStatus(err.status);
}).map(this.transformData.bind(this))
.takeUntil(action$.take(1));
}
...其中action$
是与行动相对应的可观察对象。 take(1)
是在我们收到取消操作的一项操作后确保订阅结束。