我有一个服务,并且想要查看其他服务的数据(因此当数据更改时会触发一个事件)。
// Gets data from an json file and saves it in this.data
myService.service('myService', ['$http', function($http) {
this.data = {}; // This will be returned by $watch
this.loadData = function( ){
$http.get('http://localhost/data.json').
success(function(json, status, headers, config) {
this.data = json; // This wont be returned by $watch
});
}
}]);
现在,是一些不同的服务,我调用加载函数并有一个 $watch 事件:
// Load data
myService.loadData( );
// $watch attempt #1
$rootScope.$watch('myService.data', function(data){
console.log(myService.data);
}, true);
// $watch attempt #2
$rootScope.$watch(function(){
return myService.data;
}, function(newVal, oldVal){
console.log(newVal);
});
两次 $watch 尝试都会在我的 Firebug 控制台中显示:{}(来自 this.data = {};) 但是 this.data = json;不会显示。
我做错了什么?有没有办法在数据更改时获取事件?
非常感谢。
最佳答案
您将 data
设置为错误的对象,因为 success
回调中的上下文 (this
) 会有所不同。简单的解决方法是使用一些变量来引用服务上下文,例如 var self = this :
this.loadData = function() {
var self = this;
$http.get('http://localhost/data.json').
success(function(json, status, headers, config) {
self.data = json;
});
}
关于javascript - AngularJS:$watch 服务中的其他服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26673478/