微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 如何为变量AngularJS分配$http.get响应

参见英文答案 > How to access the correct `this` inside a callback?                                    10个
堆栈溢出有很多类似的问题,但使用这些提示没有帮助.

我正在学习angular.js并在API上试验$http.get,但在将变量分配给变量时遇到了问题.

以下get请求在加载时运行. (这是我的app.js文件)

    var app = angular.module('store',[]);
    app.controller("StoreController", function($scope,$http){
        var request = $http.get('/test').then(function (response) {
            $scope.data = response;
            return response; 
        });
        request.then(function (data) {
            this.products = $scope.data
        });
    });

以下是请求的响应(我可以在浏览器的控制台视图中看到这一点,但数据未显示.)

    [
        {
        name: 'Dowayne',
        surname: 'Breedt',
        catchphrase: 'wallawallabingbangamIright?',
        reviews: [
                 {
                 stars: 5,
                 body: 'i love stuff',
                 soldOut: false,
                 },
                 {
                 stars: 4,
                 body: 'meh',
                 soldOut: true,
                 },
                 {
                 stars: 3,
                 body: 'shittake mushrooms',
                 soldOut: false,
                 },
                 ]
       }
    ];

这是所有垃圾数据(仅供练习),但我不能为我的生活理解为什么它不会显示在HTML页面上,如果我将上面的片段直接分配给this.products,那么它完美地工作/

我错过了什么?

谢谢.

解决方法:

当使用Promises然后使用.data属性获取数据.

var app = angular.module('store',[]);
 app.controller("StoreController", function($scope,$http){
    var request = $http.get('/test').then(function (response) {
        $scope.data = response.data;
        return response.data; 
    });
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐