如何获取$http.get请求的响应数据?

How to acquire response data from a $http.get request?

我有以下控制器。

spaModule.controller("galleryController", function($http, $scope) {
    var test;
    $http.get("resources/php/gallery.php").success(function(response){
        test = response;
    });
    console.log(test);
});

此控制器向 PHP 文件发送获取请求,其中 returns 一些 JSON 包含我在特定目录中的所有图像的文件名。我知道我可能应该为此使用一项服务,但我只会在一个控制器中使用这些信息,所以我宁愿将它包含在这个控制器中。

我需要从匿名函数内部获取响应数据到控制器的范围内,以便我可以使用 JSON 数据创建一个画廊指令。

我添加到这个问题的代码是我尝试这样做的。我想我的问题可能是 .success 函数有它自己的范围,或者可能是 $http 对象,所以我在 "nested" 范围内。也就是说,我需要让 JSON 超出匿名函数的范围,进入 .success/$http 的范围,然后从该范围进入控制器的范围。我不确定这是我的问题,还是如何实现的。

如何让我对控制器范围的响应 JSON?

只需将其分配给 $scope。局部 var 变量从未 Angular "scope",在回调内部或外部。

$http.get("resources/php/gallery.php").success(function(response){
    $scope.test = response;
});

如果您的意思是要 post 处理数据,则需要在 success 回调中执行此操作。由于操作是异步的,您示例中的 console.log 部分永远无法访问此数据。

$http.get("resources/php/gallery.php").success(function(response){
    // do whatever you need to do here
    var data = response.map(..);
    // then assign to $scope:
    $scope.data = data;
});

如果合适,您可以将收到的数据存储在您的范围内:

spaModule.controller("galleryController", function($http, $scope) {
   $http.get("resources/php/gallery.php").success(function(response){
       $scope.data = response;
   });
});

但这也许只有在数据量不大的情况下才应该这样做。否则,您应该将它存储在其他地方,并对其进行处理,并且仅通过 $scope

上的 ui 设置值 required
spaModule.controller("galleryController", function($http, $scope) {
    $scope.test;
    $http.get("resources/php/gallery.php")
        .success(function(response){
            $scope.test = response;
        })
        .then(function() {
            // $scope.test is set
        });
    // $scope.test is not set yet due to the async $http.get function
});

这里你在成功函数中设置了$scope.test。 Angular 会注意到范围已更新并为您完成工作。因此,您将能够在代码中的其他地方使用 $scope.test 。小心异步函数。

我希望这个回答能解决你的问题。

您忘记在控制器中注入依赖项

请更改如下控制器代码片段

spaModule.controller("galleryController", ['$scope','$http',function($scope,$http) {
var test;
 $http.get("resources/php/gallery.php").success(function(response){
    test = response;
});
console.log(test);

}]);