加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angularjs在控制器之间共享数据

发布时间:2020-12-17 07:38:50 所属栏目:安全 来源:网络整理
导读:我有一个服务,从我的服务器获取一些客户端数据: 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
我有一个服务,从我的服务器获取一些客户端数据:
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注入您的服务,然后将更改广播到控制器范围.
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 ) { });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读