我有一个服务,从我的服务器获取一些客户端数据:
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); });
我现在正在提醒,但从来没有触发过.当页面最初加载时,它会提醒“未定义”.我在控制台没有错误,所有的$注入都是正常的,但从来没有看到数据在服务中发生了变化.我在手表上做错了吗?
非常感谢
本
clientDataService.clientDataObject不是控制器范围的一部分,因此您无法观察该对象的更改.
您需要将$rootScope注入您的服务,然后将更改广播到控制器范围.
原文链接:https://www.f2er.com/angularjs/142660.html您需要将$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 ) { });