我尝试通过定期调用 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不再显示?