将$ http响应对象另存为$ scope变量 [英] Saving an $http response object as a $scope variable

查看:73
本文介绍了将$ http响应对象另存为$ scope变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I asked a related question earlier today on stackoverflow but due to both the complexity of the code (not being able to post it) and my own noviceness I wasn't able to really implement a solution from the answers given.

所以我现在的问题是,对于这样的代码:

So my question now is, for a code such as:

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

(您可以用上面的成功"代替"then",我使用"then",因为根据更新的$ http api不赞成使用成功)

(you can substitute "then" with "success" above, I use "then" because success is deprecated according to the updated $http api)

我实际上如何将响应对象保存在$ scope.data中?从目前为止的工作来看,当我稍后输入代码时,$scope.data是未定义的":

How do I actually save the response object in $scope.data? From what I've been doing so far, $scope.data is "undefined" when I later typed in the code:

console.log($scope.data3);

谢谢!

一次更新

显然,如果我将console.log($scope.data); 放到内部,控制台将显示我想要的$scope.data.但是,如果它在外面,它将在控制台中保持未定义"状态.换句话说:

Apparently if I put console.log($scope.data); inside the console will display what I want for $scope.data. But if it is outside, it will remain "undefined" in the console. In other words:

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

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

will return whatever sort of object response was. in the console, but

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

将在控制台中返回未定义".

will return "undefined" in the console.

推荐答案

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

You need to leverage the fact that $http.get returns a promise, and chain to that promise in any code that needs to access the resolved data:

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

这篇关于将$ http响应对象另存为$ scope变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆