簡體   English   中英

控制器無法訪問 Angular Service 變量

[英]Controller cannot access Angular Service variable

我的 Angular 服務有問題。 我有兩個控制器和一項服務。 基本上,第一個控制器通過 AJAX 調用獲取數據並將該數據存儲在服務上。 然后第二個控制器通過服務訪問該數據。 我已經成功地將數據從第一個控制器傳遞到服務,但是,當我從第二個控制器訪問數據時,它什么都不返回。

順便說一下,我有一個帶有 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; 
    });

}

也許你應該在服務中保存價值使用對象。在我的項目中,我總是這樣做:

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 來設置和獲取值。 試一試吧,祝好。

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

});

有關更多信息,請參閱AngularJS $rootScope.scope API 參考 - $watch

您必須編寫一個方法將數據存儲到服務中並從服務中返回數據

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

最佳實踐是在服務中調用任何 $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);

  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM