在根作用域 return 范围内创建函数

Make function in rootscope return in scope

我制作了一个带有属性的根作用域函数。它正在从数据库中获取一些数据。

我想在控制器中使用这个 rootscope 函数,并将我得到的数据放在一个变量中。

$rootScope.get_option = function(option_name){
        $http.post("server/read.php",{'subject': "options", "args": option_name })
        .success(function (response) {
            console.log(response);
            $rootScope.option_get_value = response;

        });

        if($rootScope.option_get_value){
            return $rootScope.option_get_value;
        }

    }

这就是我在控制器中所拥有的

    $scope.subscription.reduced_hourrate = $rootScope.get_option('verlaagd_tarief');
    console.log($scope.subscription.reduced_hourrate);

当我 运行 脚本时,我在日志中看到 $rootScope 函数返回正确的值。但是示波器给我返回了未定义的数据。

为什么会这样?有人帮我给我一些提示吗?

$http 进行异步调用。这意味着您的 if 语句 if($rootScope.option_get_value) ... 在您的 http 成功函数解析之前被调用。

要让它工作,你可以这样做

$rootScope.get_option = function(option_name){
    return $http.post("server/read.php",{'subject': "options", "args": option_name })
}

然后在你的控制器里面

$rootScope.get_option('verlaagd_tarief').success(function (response) {
     $rootScope.option_get_value = response;
});

但我不确定这是将数据传递给控制器​​的最佳方式。 一种常见的方法是使用 services。不使用 $rootScope

这是一个如何使用服务将数据传递给控制器​​的示例。

var app = angular.module('myApp', []);

//declare a service that make the http calls
myApp.factory('myHttpService', function($scope, $http) {

   //return the public API
    return {
        //use a callback function to return
        //the result when the promise is resolved
        get_option : function(option_name, fct){
            $http.post("server/read.php",
                 {
                      "subject": "options", 
                      "args": option_name 
                 }
            ).then(function(result){
                fct(result) //calling the callback when the promise is resolved to return the result
            })
    }
});

// the controller using myHttpService
myApp.controller('myCtrl', function($scope, myHttpService) {
   myHttpService.getOption('verlaagd_tarief', function(result){
       $scope.option_get_value = result
   })
});
$rootScope.get_option = function(option_name){
    return $http.post("server/read.php",{'subject': "options", "args": option_name    })
    .success(function (response) {
        console.log(response);
        if(response){
           return response;
        }
    });
}

当您调用 $http.post 时,调用 if 行后 return 成功,这就是您得到 "undefined" 的原因,因为响应没有不会返回数据来填充 $rootScope.option_get_value。 您正在使用“.success”($http 内的承诺:https://docs.angularjs.org/api/ng/service/$http), 当您将 return 移动到承诺中时,它只会在响应可用时启动。

在控制台中,您会看到来自响应的完整数据,因为控制台正在通过引用工作,这意味着...当您单击日志打开对象时,return 已经返回它将数据引用到控制台。