我有一个从我的服务器获取一些客户端数据的服务:
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都很好,但它似乎从未意识到数据在服务中已经改变。我在手表上做错了吗?
非常感谢 本
答案 0 :(得分:13)
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 ) { });
答案 1 :(得分:9)
另一种方法可以是:
定义新服务
app.factory('DataSharingObject', function(){
return {};
}
在我们想要存储数据的控制器中包含这项新服务
app.factory('clientDataService', function ($http, DataSharingObject) {
DataSharingObject.sharedata = ..assign it here
}
在我们想要访问数据的控制器中包含此新服务
app.factory('clientReceivingService', function ($http, DataSharingObject) {
..use it here... = DataSharingObject.sharedata
}