2014-10-31 36 views
2

我有一個服務,並且希望觀察其他服務的數據(因此當數據發生更改時觸發事件)。

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

兩個$手錶的嘗試會告訴我在我的Firebug控制檯:{}(從this.data = {};) 但this.data = json;將不會顯示。

我做錯了什麼?數據更改時有辦法獲得事件嗎?

非常感謝。

回答

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; 
     }); 
} 
+0

非常感謝,它的作品完美。我使用它,因爲它看起來很容易。 – Tream 2014-10-31 11:34:07

+1

是的,這是最簡單,也是更高性能。但綁定的人也有優點,它有點更好,不需要多一個變量。 – dfsq 2014-10-31 11:35:57

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; 
     })); 
+0

非常感謝您的回覆!我測試了兩個答案,並且兩個都很好! – Tream 2014-10-31 11:33:29