我有一项从服务器中获取一些客户端数据的服务:
app.factory('clientDataService', function ($http) { var clientDataObject = {}; var cdsService = { fetch: function (cid) { //$http returns a promise, which has a then function, which also returns a promise var promise = $http.get('/clients/stats/' + cid + '/').then(function (response) { // The then function here is an opportunity to modify the response console.log(response); // The return value gets picked up by the then in the controller. clientDataObject = {'data': response.data, 'currentClientID': cid}; return clientDataObject; }); // Return the promise to the controller return promise; } }; return cdsService; });
然后在一个控制器中执行:
//get stats clientDataService.fetch($scope.id).then(function (response) { $scope.client_data = { 'statistics': response.data } });
一切都很好。但是,我正在尝试从 该服务上的另一个控制器进行监视,以在数据更改时更新其范围,而不是 必须重新启动http请求:
$scope.$watch('clientDataService.clientDataObject', function (cid) { alert(cid); });
我现在只是提醒,但从未触发过。页面最初加载时,它会发出“未定义”的警报。我在控制台中没有任何错误,并且所有$ injects都很好,但是似乎从未意识到服务中的数据已更改。我在手表上做错了吗?
非常感谢
clientDataService.clientDataObject不在控制器范围内,因此您无法监视该对象的更改。您需要将$ rootScope注入服务中,然后将更改广播到控制器作用域。
app.factory('clientDataService', function ($rootScope, $http) { var clientDataObject = {}; var cdsService = { fetch: function (cid) { var promise = $http.get('/clients/stats/' + cid + '/').then(function (response) { // The then function here is an opportunity to modify the response console.log(response); // The return value gets picked up by the then in the controller. clientDataObject = {'data': response.data, 'currentClientID': cid}; $rootScope.$broadcast('UPDATE_CLIENT_DATA', clientDataObject); return clientDataObject; }); // Return the promise to the controller return promise; } }; return cdsService; });
然后在控制器中,您可以使用以下命令监听更改:
$scope.$on('UPDATE_CLIENT_DATA', function ( event, clientDataObject ) { });