简体   繁体   English

控制器无法访问 Angular Service 变量

[英]Controller cannot access Angular Service variable

I have a problem with my Angular Service.我的 Angular 服务有问题。 I have two controllers and one service.我有两个控制器和一项服务。 Basically the first controller gets data via AJAX call and store that data on the service.基本上,第一个控制器通过 AJAX 调用获取数据并将该数据存储在服务上。 The second controller then access that data via service.然后第二个控制器通过服务访问该数据。 I have successfully passed the data from the 1st controller to the service however, when I access the data from the 2nd controller it returns nothing.我已经成功地将数据从第一个控制器传递到服务,但是,当我从第二个控制器访问数据时,它什么都不返回。

I have one view with 2 controllers by the way.顺便说一下,我有一个带有 2 个控制器的视图。

Thanks谢谢

Service服务

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

Controller 1控制器 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){
        });

    }

}

Controller 2控制器 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; 
    });

} }

May be you should save the value use object in service.In my project, i always do like this:也许你应该在服务中保存价值使用对象。在我的项目中,我总是这样做:

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

Then, in your controller.然后,在您的控制器中。 You should call service.toogle_sub_task to set and get value.您应该调用 service.toogle_sub_task 来设置和获取值。 Just give it a try.Best wishes.试一试吧,祝好。

Because SharedDataService is not on $scope , the first argument of the $watch method needs to be a watchExpression function instead of an Angular expression string .因为SharedDataService不在$scope$watch方法的第一个参数需要是watchExpression函数而不是Angular 表达式字符串

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;
            }
        }    
    });

});

For more information, see AngularJS $rootScope.scope API Reference - $watch .有关更多信息,请参阅AngularJS $rootScope.scope API 参考 - $watch

you have to write a method to store the data into service and return the data from service您必须编写一个方法将数据存储到服务中并从服务中返回数据

   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
   };
});

and in controller call并在控制器调用中

SharedDataService.setSubTask(response.data);

to set the data...设置数据...

try it尝试一下

    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 );
 });

The best practice is to make any $http/resource calls in services and not in controller or directives directly.最佳实践是在服务中调用任何 $http/resource 调用,而不是直接在控制器或指令中调用。 This makes the code more module and less interlinked.这使得代码更加模块和更少的相互关联。

You should ideally have理想情况下你应该有

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;
    });

and use it like并像使用它一样

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);

  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM