首页 > 技术文章 > AngularJS $http返回的数据类型

happyfish321 2017-05-09 16:08 原文

AngularJS 1.6.4 调用$http服务,是如下样式:

$http.get('/someUrl', config).then(successCallback, errorCallback);

 

项目中代码:

angular.module("myApp").controller("mainCtrl",["$http","$scope",function($http,$scope){
	$http.get("data/positionList.json").then(function(resp){
		$scope.lists=resp;
		console.log($scope.lists);
	},function(){

	});
}]);

一直在纠结怎么lists就是get不到正确的数据,在页面中展示的内容很奇怪。 后来在控制台打印出来结果信息才发现:

请求结果resp的是包含请求数据,状态码,回应头信息,请求字符码的对象。在控制台结果如下:

Object { data: Array[4], status: 200, headers: wd/<(), config: Object, statusText: "OK" }

展开如下:

 

所以要获取数据,应该获取对象中的data属性,使用resp.data:

angular.module("myApp").controller("mainCtrl",["$http","$scope",function($http,$scope){
    $http.get("data/positionList.json").then(function(resp){
        $scope.lists=resp.data;
        console.log($scope.lists);
    },function(){

    });
}]);

这次获取的对象才是数据:

Array [ Object, Object, Object, Object ]

推荐阅读