[英]Get function return value inside promise on spyOn service - Jasmine Angularjs
[英]AngularJS promise return value from inside a service seems to change
每當我輪詢新數據時,我就使用一項服務進行一系列API調用:
angular.module('dashboardApp')
.service('data', function($http, $q) {
var _this = this;
_this.server = function() {
/*get server address*/
};
_this.polling = function() {
_this.myData = {};
console.log('_this.myData emptied');
}
_this.getData = function(){
var deferred = $q.defer();
_this.server().then(function(serverconf) {
/*...*/
deferred.resolve();
};
var getDataA = function(){
/*---*/
_this.myData = {a : 'a'};
};
var getDataB = function(){/*...*/};
var getDataC = function(){/*...*/};
var promiseA = deferred.promise.then(getDataA);
var promiseB = deferred.promise.then(getDataB);
var promise = $q.all([pomiseA,pomiseB]).then(function(resp){
/* do something here */
}).then(getDataC).then(function(resp2){
/*...*/
_this.myData = {c : 'c'};
return _this.myData;
});
return promise;
};
return {
getData = _this.getData,
polling = _this.polling,
};
};
我正在整個服務中的API調用期間更改數據。 而且我可以看到,每次API調用成功后,控制器內的數據都會發生變化,從而進行調用。
var polling = function() {
data.getData().then(function(myData) {
$scope.myDataset = myData;
setTimeout(function() {
data.polling();
polling();
}, 3000);
});
};
$scope.$watch('myDataSet', function(newVal, oldVal) {
console.debug(newVal);
}, true);
//output:
//{}
//{a:'a'}
//{b:'b'}
我停用了其他所有功能,因此我很確定新數據來自服務本身。
編輯:當我簡化代碼時,忘記了一些重要的東西。
多虧了NewDev的幫助,我認為問題在於我在每個諾言中都返回了$http
-promise。
但是由於我沒有足夠的時間進行更深入的研究,因此我制定了一個快速的解決方法來解決我的問題:
var polling = function() {
data.getData().then(function(myData) {
$scope.returned = true;
$scope.myDataSet = myData;
setTimeout(function() {
data.polling();
polling();
}, 3000);
});
};
$scope.$watch('myDataSet', function(newVal, oldVal) {
if($scope.returned === true){
$scope.myDataSet = newVal;
$scope.returned = false;
}else{
$scope.myDataSet = oldVal;
}
}, true);
這樣,我將監視在解決所有承諾后是否返回了新數據,並以此方式控制更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.