无法使用$ http angularjs获取结果数据 [英] Can't get result data with $http angularjs

查看:82
本文介绍了无法使用$ http angularjs获取结果数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用$ http,但是为什么它返回空结果?

I'm trying to use $http, but why it return null result?

angular.module('myApp')
.factory('sender', function($http) {
    var newData = null;
    $http.get('test.html')
        .success(function(data) {
            newData = data;
            console.log(newData)
        })
        .error(function() {
            newData = 'error';
        });
    console.log(newData)
    return newData
})

控制台说: http://screencast.com/t/vBGkl2sThBd4 .为什么我的newData首先为null,然后定义?如何正确执行?

Console say: http://screencast.com/t/vBGkl2sThBd4. Why my newData first is null and then is defined? How to do it correctly?

推荐答案

正如YardenST所说,$http是异步的,因此您需要确保所有函数或显示逻辑都依赖于$http.get(),相应地获取句柄.实现此目的的一种方法是利用$http返回的承诺":

As YardenST said, $http is asynchronous so you need to make sure that all functions or display logic that are dependent on the data that is returned by your $http.get(), gets handle accordingly. One way to accomplish this is to make use of the "promise" that $http returns:

Plunkr演示

var myApp = angular.module('myApp', []);

myApp.factory('AvengersService', function ($http) {

    var AvengersService = {
        getCast: function () {
            // $http returns a 'promise'
            return $http.get("avengers.json").then(function (response) {
                return response.data;
            });
        }
    };

    return AvengersService;
});


myApp.controller('AvengersCtrl', function($scope, $http, $log, AvengersService) {
    // Assign service to scope if you'd like to be able call it from your view also
    $scope.avengers = AvengersService;

    // Call the async method and then do stuff with what is returned inside the function
    AvengersService.getCast().then(function (asyncCastData) {
            $scope.avengers.cast = asyncCastData;
    });

    // We can also use $watch to keep an eye out for when $scope.avengers.cast gets populated
    $scope.$watch('avengers.cast', function (cast) {
        // When $scope.avengers.cast has data, then run these functions
        if (angular.isDefined(cast)) {          
            $log.info("$scope.avengers.cast has data");
        }
    });
});

这篇关于无法使用$ http angularjs获取结果数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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