angular 1.5无范围访问http.get中的数据

angular 1.5 access data in http.get without scope

本文关键字:get 数据 http 访问 范围 angular      更新时间:2023-09-26

我使用的是Angular 1.5。

我无法访问我的数据,从http.get到http.get。让我解释一下:

我有我的组件:

(function(){
'use strict';
class myComponent {
    constructor(
        $http,
        $scope)
    {
        var self = this;
        self.test="this is a test";
        $http.get(MYAPI).then(function(response){
        self.MYDATA = response.data;
        console.log(self.MYDATA)
        });
        console.log(self.test)
        console.log(self.MYDATA)
    }
}
angular.module('myApp')
.component('myApp.test', {
    templateUrl: 'myTemplate.html',
    controller: myComponent,
    controllerAs:'vm',
}); 
})();

控制台。日志给我:

这是测试的测试-->

未定义-->输出http.get

http.get 中的对象{id:1…}-->

所以我无法从http.get访问我的数据,这正是我想要的。

$http.get是一个异步调用,这意味着程序执行不等待从服务器获取数据。

因此,当位于$http.get()之外的console.log(self.MYDATA)被执行时,数据还没有从服务器中提取,这就是为什么您得到undefined error的原因。

为了解决这个问题或处理异步调用,您可以执行以下操作:

 var promise = $http.get(MYAPI);

然后在回调的帮助下以以下方式访问数据:

  promise.then(
            function successCallBack(response)
                {
                   self.MYDATA = response.data;
                   console.log(self.MYDATA)
                }
            ).then(
                function errorCallBack(response)
                {
                    console.log(response);
                }           
            );

这里有一篇关于回调的好文章,可以帮助你!