将$ http响应对象保存为$ scope变量

时间:2015-10-02 17:27:27

标签: angularjs http

我今天早些时候在stackoverflow上问了一个相关的问题,但是由于代码的复杂性(无法发布)和我自己的新手,我无法从给出的答案中真正实现解决方案。

所以现在我的问题是,代码如:

$http.get(ArbitraryInput).then(function (response) {$scope.data = response});

(你可以用上面的“成功”替换“then”,我使用“then”因为根据更新的$ http api弃用了成功)

如何在$ scope.data中实际保存响应对象?从我到目前为止所做的事情来看,$scope.data在我后来输入代码时是“未定义的”:

console.log($scope.data3);

谢谢!

更新一次

显然,如果我将console.log($scope.data); 置于内,控制台将显示我想要的$scope.data。但如果它在外面,它将在控制台中保持“未定义”。换句话说:

$http.get(ArbitraryInput).then(function (response) {$scope.data = response; console.log($scope.data);});

将返回任何类型的对象响应。在控制台中,但

$http.get(ArbitraryInput).then(function (response) {$scope.data = response;});
console.log($scope.data);

将在控制台中返回“undefined”。

5 个答案:

答案 0 :(得分:6)

您需要利用$ http.get返回一个promise的事实,并在任何需要访问已解析数据的代码中链接到该promise:

app.controller('Ctrl', function($scope, mainInfo){
    var request = $http.get(ArbitraryInput).then(function (response) {
        $scope.data = response; 
        return response; // this will be `data` in the next chained .then() functions
    });

    request.then(function (data) {/* access data or $scope.data in here */});


    $scope.someFunction = function () {
        request.then(function (data) {/* access data or $scope.data in here */);
    };
}) ;

答案 1 :(得分:5)

已经回答了问题,但是想要在需要立即数据的情况下提供备用解决方案。您可以将该数据解析为路由中的依赖项,而不是直接在您的控制器/指令中调用$ http服务,因此数据可立即使用:

angular.module('myApp')
    .controller('myCtrl', ['myData', function(myData) {
        var self = this;
        self.data = myData;
    }]);

然后您的控制器可能如下所示:

<pre>{{ctrl.data|json:4}}</pre>

在你看来:

Build

将所有数据显示为JSON,而无需在控制器中调用$ http。

答案 2 :(得分:3)

试试这个:

$http.get(ArbitraryInput).then(function (response) {
    $scope.data =     response;
    console.log($scope.data);
});

$ http.get是asynchronous。 另见AJAX

的解释

答案 3 :(得分:2)

请注意,这是一个承诺(异步请求),所以如果您做了类似的事情

$http.get(ArbitraryInput).then(function (response) {$scope.data = response;});
console.log($scope.data)

它可能没有记录任何内容,因为您在请求完成之前尝试记录它 所以你可能需要使用这样的东西

$http.get(ArbitraryInput).then(function (response) {
$scope.data = response;
console.log($scope.data);
});

因此您确定在分配给$ scope.data

之后将执行console.log

答案 4 :(得分:1)

这是一个实际答案,由用户Kirill Slatin提供。答案底部的实际使用示例。

如果像我一样,你需要将该响应对象用作范围变量,这就是诀窍:

这将在控制台中返回“undefined”,与我一样,您可能无法在页面上使用该响应数据:

$http.get(ArbitraryInput).then(function (response) {$scope.data = response;});
console.log($scope.data);

但是,这应该有效:

    $http.get(ArbitraryInput)
         .then(function (response) {
            $scope.data = response;
            $scope.$apply()
});

$scope.$apply()将保留响应对象,以便您可以使用该数据。

-

为什么需要这样做?

我一直在尝试为我的食谱应用创建一个“编辑”页面。 我需要使用所选配方的数据填充表单。 在发出我的GET请求并将响应数据传递给$ scope.form后,我什么都没有...... $scope.$apply()Kirill Slatin帮了大忙。干杯队友!

以下是来自editRecipeController的示例:

  $http.get('api/recipe/' + currentRecipeId).then(
    function (data) {
      $scope.recipe = data.data;
      $scope.form = $scope.recipe;
      $scope.$apply()
    }
);

希望有所帮助!