加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 18:00:52 所属栏目:安全 来源:网络整理
导读:我今天早些时候在stackoverflow上问了一个相关的问题,但是由于代码的复杂性(无法发布)和我自己的新手,我无法从给出的答案中真正实现解决方案. 所以现在我的问题是,对于如下代码: $http.get(ArbitraryInput).then(function (response) {$scope.data = respon
我今天早些时候在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”.

解决方法

您需要利用$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 */);
    };
}) ;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读