在Angular JS中设置远程数据的变量

问题描述 投票:0回答:2

我在html代码中调用函数Allow(),如果返回true,将允许用户编辑数据。

函数$scope.GetCurrentStatus()$scope.GetCurrentStatus()都是同步的。

但它在Allow()方法中返回以下错误。

Type Error: Cannot read property 'UserType' of undefined

帮我处理这个情况。

//LoadStatus
$scope.GetCurrentStatus = function () {
    var defer = $q.defer();
    $http({
        method: "POST",
        url: "../Documentation/Documentation.aspx/GetStatus",
        data: {}
    })
    .then(function (response) {
       defer.resolve(response.data.d);
        $scope.Status = response.data.d;
    }),
    function (error) { data, status };
}

$scope.GetCurrentStatus();

//Load AccessRole 
$scope.GetAccessRole = function () {
    var defer = $q.defer();
    $http({
        method: "POST",
        url: "../Documentation/Documentation.aspx/GetAccessRole",
        data: {}
    })
   .then(function (response) {
       defer.resolve(response.data.d);
       $scope.Access = response.data.d;
   }),
   function (error) { data, status };
};

$scope.GetAccessRole();

$scope.Allow = function () {
    if ($scope.Access.UserType == 'Admin' || !($scope.Status.Status == 'CC' || $scope.Status.Status == 'CD'))
        return true;
    return false;
}
javascript angularjs
2个回答
2
投票

虽然函数$scope.GetCurrentStatus()$scope.GetCurrentStatus()在同步fasion中被调用,但它们中有一些异步代码。

不幸的是,你的变量$scope.Access$scope.Status只在这些异步方法中创建。因此,在设置范围变量之前,需要等待网络响应。

一个解决方法是在控制器的某个上方声明$scope.Access$scope.Status

$scope.Access = {};
$scope.Status = {};

0
投票

之所以发生这种情况,是因为您在设置由异步调用引起的任何值设置的实际$scope.Allow变量之前使用$scope.Access。所以你可以在推迟成功之前调用$scope.Allow方法或者在调用$scope.access方法之前设置$scope.status$scope.Allow

   $scope.Access = {};
   $scope.Status = {};
   $scope.GetCurrentStatus() = function(){
       return $http.get('http://UR_URL');
   });
   $scope.GetAccessRole = function(){
       return $http.get('http://UR_URL');
   });

并用作

 $scope.GetCurrentStatus().then(function(response){
   $scope.Status = response.data.d;
 });
 $scope.GetAccessRole().then(function(response){
   $scope.Access = response.data.d;
 });

然后调用$scope.Allow方法

© www.soinside.com 2019 - 2024. All rights reserved.