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 ]