控制器无法访问 Angular 服务变量

Controller cannot access Angular Service variable

我的 Angular 服务有问题。我有两个控制器和一项服务。基本上,第一个控制器通过 AJAX 调用获取数据并将该数据存储在服务上。然后第二个控制器通过服务访问该数据。我已经成功地将数据从第一个控制器传递到服务,但是,当我从第二个控制器访问数据时,它 returns 什么都没有。

顺便说一句,我有一个视图和 2 个控制器。

谢谢

服务

app.service('SharedDataService', function () {
  // Holds subtask that will be passed to other controllers
  // if SharedDataService is invoke.
  var _subTask = {};
  return {
    subTask : _subTask
  };
});

控制器 1

app.controller('MainCategoryController',function($scope,$http,SharedDataService){

    $scope.loadSubtask = function(m_uid){
        $http({
            method: 'POST',
            url: $locationProvider + 'query_stasks',
            data: {
                m_uid: m_uid
            }
        }).then(function successCallback(response) {
                SharedDataService.subTask = response.data;
            },function errorCallback(response){
        });

    }

}

控制器 2

app.controller('SubTaskController',function($scope,$http,$location,$rootScope,SharedDataService){



    $scope.$watch('SharedDataService.subTask', function(newValue,oldValue){
        console.log("ni sud');");
        if (newValue !== oldValue) {
            $scope.subTasks = newValue;
        }   
        return SharedDataService.subTask; 
    });

}

你必须编写一个方法来将数据存储到服务中,return 从服务中存储数据

   app.factory('SharedDataService', function () {
   // Holds subtask that will be passed to other controllers
   // if SharedDataService is invoke.
  var _subTask = [];
   function setSubTask = function(data){
    _subTask = data;
   };
   return {
   subTask : _subTask,
   setSubTask:setSubTask
   };
});

并在控制器中调用

SharedDataService.setSubTask(response.data);

设置数据...

试一试

    app.service('SharedDataService', function () {
   this._subTask ={};
});

 // keep code same  1st controller
app.controller('MainCategoryController',function($scope,$http,SharedDataService){

$scope.loadSubtask = function(m_uid){
    $http({
        method: 'POST',
        url: $locationProvider + 'query_stasks',
        data: {
            m_uid: m_uid
        }
    }).then(function successCallback(response) {
            SharedDataService._subTask = response.data;
        },function errorCallback(response){
    });

   }

  }

// 2nd controller

  app.controller('SubTaskController',function($scope,$http,$location,$rootScope,SharedDataService){

 console.log(SharedDataService._subTask );
 });

也许你应该在 service.In 我的项目中保存值使用对象,我总是这样做:

app.service('SharedDataService', function () {
  var service = {};
  service._subTask = '';
  service.toogle_sub_task = function(v){
    if(v){
        service._subTask = v;
    }
    return service._subTask;
  }
  return service;
});

然后,在你的控制器中。您应该调用 service.toogle_sub_task 来设置和获取值。就给它一个try.Best的祝福吧。

因为SharedDataService不在$scope上,$watch method needs to be a watchExpression function instead of an Angular expression string的第一个参数。

app.controller('SubTaskController',function($scope,$http,$location,$rootScope,SharedDataService){

    $scope.$watch(
        function watchExpression() {return SharedDataService.subTask},
        function listener (newValue,oldValue){
            console.log("ni sud");
            if (newValue !== oldValue) {
                $scope.subTasks = newValue;
            }
        }    
    });

});

有关详细信息,请参阅 AngularJS $rootScope.scope API Reference - $watch

最佳做法是在服务中而不是直接在控制器或指令中进行任何 $http/resource 调用。这使得代码更模块化,更少相互关联。

理想情况下,您应该

app.factory('SharedDataService', function ($http) {
         var subtasks = [];
         var saveSubtasks = function(sub){
           subtasks = sub;
           console.log(subtasks)
         }
         var tasks = {
          loadSubtasks : function(m_uid){
            $http({
                      method: 'POST',
                      url: $locationProvider + 'query_stasks',
                      data: {
                          m_uid: m_uid
                      }
                }).then(function(data){
                  saveSubtasks(data);
                });
          },
          getSubtasks : function(){
            return subtasks;
            }
          }
        return tasks;
    });

并像

一样使用它
app.controller('SharedDataService',function($scope,SharedDataService){
  $scope.load = function(val){
    SharedDataService.loadSubtasks(val);
  }
});

app.controller('SubTaskController',function($scope,SharedDataService){
  $scope.get = function(){
    $scope.subtasks = SharedDataService.getSubtasks();
    console.log($scope.subtasks);

  }
});