一、问题描述:
电脑安装的angular1.6.7版本,项目中使用了$http.get( ).success( ),控制台报错:
$http.get(...).success is not a function
就是说找不到success方法,同样也找不到error方法。
二、原因分析
经查询,从1.6版本开始,angular正式移除了success和error方法。从1.5版本开始,angular多出来then( )方法。因此,从1.6版本后不能使用success和error方法,可以采用then( )方法替代。
三、使用$http.get( ).then( )替代
原success代码示例:
angular.module("app").controller("mainCtrl",["$http","$scope",function ($http,$scope) {
$http.get('data/positionList.json').success(function (resp) {
$scope.list=resp;
console.log($scope.list);
});
}])
直接将success换成then:
angular.module("app").controller("mainCtrl",["$http","$scope",function ($http,$scope) {
$http.get('data/positionList.json').then(function (resp) {
$scope.list=resp;
console.log($scope.list);
});
}])
发现得到的数据有差异:
在使用success时得到的就是标红框部分数组,而使用then时得到的却是一个对象,数组成了对象的一个属性。
因此在形参后面加上data属性即可解决:
angular.module("app").controller("mainCtrl",["$http","$scope",function ($http,$scope) {
$http.get('data/positionList.json').then(function (resp) {
$scope.list=resp.data;
console.log($scope.list);
});
}])
四、备注:
$http.post( ).success( )
可正常使用,不会报错;
使用 $http.post( ).then( )
反而会报错。