【问题标题】:How to watch array or object change in service? [duplicate]如何观察服务中的数组或对象变化? [复制]
【发布时间】:2015-11-06 01:17:34
【问题描述】:

我的 Angular 应用中有服务。该服务通过一些操作提供对数组的访问(许多控制器都提供访问权限,它们都需要监视此变量)。

但是如何观察这项服务的变化呢?它没有$scope,也不知道在哪里找$watch?

这是我的服务代码:

(function(){
    angular.module('something')
        .factory('MasterService',['$http', function($http){
            var service = this;
            var data = {                
                operations: [] // this array need to be accessible from controllers
            };

            $http.get('some/url').success(function(data){
                // here we mofidy array with loaded from server
                data.operations = angular.copy(data.operations);
            });

            return {
                // controllers will receive operations via this method
                getOperations: function () {
                    return data.operations;
                }
            };
        }])
})();

如何在该服务中观察操作变量?我需要添加类似的内容:

        operations.$watch(function(){
            //make some actions with operations
        });

【问题讨论】:

  • 您能解释一下为什么需要从服务中观看吗?无论如何,您需要有足够的空间观看。
  • 你可以创建一个范围,为了你的观看乐趣,不是吗?
  • 你能举个例子说明为什么你需要观察服务的变化吗?
  • 当控制器中的某些内容发生更改(有人添加新内容或更改)时,在服务中我需要更新主数据(这取决于该数据)(也许我还需要一个控制器???)。

标签: javascript angularjs


【解决方案1】:

控制器中,您可以 $watch 一个返回服务数据的函数:

$scope.$watch(function() {
  return MasterService.getOperations();
}, function(newVal, oldVal) {
  // do something with newVal;
});

【讨论】:

    【解决方案2】:

    $watchers 在您的数据在 Angular 之外发生变化时很有用,并且在 Angular 应用程序中使用它是非常多余的,因为摘要周期已经有观察者,您最好检查我们的逻辑。
    使用这种方法,你甚至不需要 $watcher

    (function(){
        angular.module('something')
            .factory('MasterService',['$http', function($http){
                var service = this;
                var data = {                
                    operations: [] // this array need to be accessible from controllers
                };
                //ommitted
                return {
                    // controllers will receive operations via this method
                    operations: data.operations
                };
            }])
    })();
    

    在控制器中

    $scope.operators = MasterService.operators;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-31
      • 2015-08-20
      • 2017-08-21
      • 1970-01-01
      • 1970-01-01
      • 2011-07-03
      • 2014-01-07
      • 2018-03-01
      相关资源
      最近更新 更多