Angular 1.6提示$http.get(...).success is not a function

来源:互联网 发布:天猫淘宝京东的区别 编辑:程序博客网 时间:2024/06/05 14:09

1.在使用Angular 1.6版本的$http服务时会抛出异常:$http.get(...).success is not a function

或者$http(...).success is not a function

异常代码如下:

[javascript] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. //请求api  
  2. $http.get('/api/user/showname', {  
  3.     params: {  
  4.         name: '张三'  
  5.     }  
  6. }).success(function (data, status, config, headers) {  
  7.     console.info(data);  
  8.     alert(data);  
  9. }).error(function (data) {  
  10.     console.info(data);  
  11. });  

异常信息如下:

[javascript] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. angular.js:14328TypeError: $http.get(...).success is not a function  
  2.     at new <anonymous> (test2.html:20)  
  3.     at Object.invoke (angular.js:4842)  
  4.     at R.instance (angular.js:10695)  
  5.     at n (angular.js:9572)  
  6.     at g (angular.js:8881)  
  7.     at angular.js:8746  
  8.     at angular.js:1843  
  9.     at m.$eval (angular.js:17972)  
  10.     at m.$apply (angular.js:18072)  
  11.     at angular.js:1841  

究其原因,新版本的AngularJs中取消了success和error,用promise规则。

更改写法:

[javascript] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. $http.get('/api/user/showname2', {  
  2.     params: {  
  3.         name: '张三',  
  4.         age: 'abc'  
  5.     }  
  6. }).then(function (result) {  //正确请求成功时处理  
  7.     console.info(result);  
  8.     alert(result.data);  
  9. }).catch(function (result) { //捕捉错误处理  
  10.     console.info(result);  
  11.     alert(result.data.Message);  
  12. });  
正常相应:

异常400相应:



更多:

AngularJS $http简介1

使用$watch来监视属性或对象的变化

0 0