AngularJS:$在服务中观看其他服务

时间:2014-10-31 11:20:41

标签: javascript angularjs

我有一项服务,并希望观看其他服务的数据(因此,当数据发生变化时会触发事件)。

// 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
            });
    }
}]);

现在,是一些不同的服务,我调用load函数并有一个$ 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-Console中显示:{}(来自this.data = {};) 但是这个.data = json;不会显示。

我做错了什么?有没有办法在数据发生变化时获取事件?

非常感谢。

2 个答案:

答案 0 :(得分:2)

您的第二次尝试是正确的,但您的服务有问题:

关键字this在异步回调中丢失了它的上下文。

this.loadData = function( ){
    $http.get('http://localhost/data.json').
        success(function(json, status, headers, config) {
            // the keyword this lost it's context here
        });
}

您可以使用angular.bind来保留正确的上下文:

this.loadData = function( ){
    $http.get('http://localhost/data.json').
        success(angular.bind(this, function(json, status, headers, config) {
            this.data = json;
        }));

答案 1 :(得分:2)

您正在将data设置为错误的对象,因为this回调内的上下文(success)会有所不同。简单的解决方法是使用某些变量来引用服务上下文,例如var self = this

this.loadData = function() {
    var self = this;
    $http.get('http://localhost/data.json').
        success(function(json, status, headers, config) {
            self.data = json;
        });
}
相关问题