我嘗試通過$ http定期調用DataService來獲取json文件。AngularJS手錶定期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)
// ...
}
的DataService:
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(){/ *當前返回的內容* /}嗎? – lort
抱歉,我在編輯問題的代碼時刪除了內部函數聲明。現在更新的版本 – IHeartAndroid