【发布时间】:2013-10-04 09:32:48
【问题描述】:
我尝试通过定期调用 DataService 来通过 $http 获取 json 文件。
然后我想使用 $watch 功能来响应任何数据更改。但是,监视功能永远不会被触发超过一次。为什么?
var app = angular.module('myApp', ['ngRoute']).
config(['$routeProvider', function ($routeProvider) {
//...
}])
.
run(function ($rootScope, $timeout, $location, DataService) {
$rootScope.jsonData = {}
var delaytime = 10 * 1000;
$rootScope.jsonData = DataService.getData();
$timeout(function repeat() {
console.log("in repeat")
$rootScope.jsonData = DataService.getData();
$timeout(function () {
console.log("in inner repeat")
repeat();
}, delaytime
);
}, delaytime
);
console.log("xxx")
console.log($rootScope.jsonData)
$rootScope.$watch('jsonData', reactToDataChange($rootScope, $location));
})
;
function reactToDataChange($rootScope, $location) {
console.log("yyy")
console.log($rootScope.jsonData)
// ...
}
数据服务:
app.service('DataService', function ($http) {
var data = null;
function setData(newdata) {
data = newdata;
}
return {
getData: function () {
console.log("getting data");
var rand = "?rand=" + Math.random() * 10000;
$http.get('data/bla.json' + rand, {cache: false})
.success(function (newdata) {
console.log(newdata);
setData(newdata);
})
.
error(function (data, status, headers, config) {
console.log("error");
console.log(status)
});
return data;
}
};
});
控制台显示:
getting data
xxx
null
yyy
null
new data:[object Object]
Object {bla: Object}
in repeat
getting data
new data:[object Object]
Object {bla: Object}
in inner repeat
in repeat
getting data
new data:[object Object]
Object {bla: Object}
in inner repeat
in repeat
...
为什么 yyy 不再显示?
【问题讨论】:
-
我在您的 DataService 中看不到
getData()的定义,我想知道它是如何工作的。 DataService中的return中不应该有getData: function(){ /* contents of current return */ }吗? -
很抱歉,当我编辑问题的代码时,内部函数声明被我删除了。现在更新版本