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

本文介绍在使用AngularJS 1.6版本时遇到的$http服务异常问题:$.success is not a function,并提供了相应的解决方案,即如何将旧版的成功和错误回调更改为Promise的then和catch方法。

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. });  
//请求api
$http.get('/api/user/showname', {
    params: {
        name: '张三'
    }
}).success(function (data, status, config, headers) {
    console.info(data);
    alert(data);
}).error(function (data) {
    console.info(data);
});

异常信息如下:

[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  
angular.js:14328TypeError: $http.get(...).success is not a function
    at new <anonymous> (test2.html:20)
    at Object.invoke (angular.js:4842)
    at R.instance (angular.js:10695)
    at n (angular.js:9572)
    at g (angular.js:8881)
    at angular.js:8746
    at angular.js:1843
    at m.$eval (angular.js:17972)
    at m.$apply (angular.js:18072)
    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. });  
$http.get('/api/user/showname2', {
    params: {
        name: '张三',
        age: 'abc'
    }
}).then(function (result) {  //正确请求成功时处理
    console.info(result);
    alert(result.data);
}).catch(function (result) { //捕捉错误处理
    console.info(result);
    alert(result.data.Message);
});
正常相应:

异常400相应:



更多:

AngularJS $http简介1

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

/** * Created by wupeng5 on 2016/5/9. */ var app = angular.module("app",['ui.router','oc.lazyLoad','tableKillModule','selectModule',"select2Module"]).config(function($stateProvider,$controllerProvider,$compileProvider,$filterProvider,$provide,$urlRouterProvider,$httpProvider){ $urlRouterProvider.otherwise('login'); //引入$stateProvider对象,为动态路由做准备 app.register = { stateProvider:$stateProvider } //$locationProvider.html5Mode(true); $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; $httpProvider.defaults.headers.common["Accept"] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'; $httpProvider.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest'; $httpProvider.defaults.transformRequest = [function(data) { /** * The workhorse; converts an object to x-www-form-urlencoded serialization. * @param {Object} obj * @return {String} */ var param = function(obj) { var query = ''; var name, value, fullSubName, subName, subValue, innerObj, i; for (name in obj) { value = obj[name]; if (value instanceof Array) { for (i = 0; i < value.length; ++i) { subValue = value[i]; fullSubName = name + '[' + i + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + '&'; } } else if (value instanceof Object) { for (subName in value) { subValue = value[subName]; fullSubName = name + '[' + subName + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + '&'; } } else if (value !== undefined && value !== null) { query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&'; } } return query.length ? query.substr(0, query.length - 1) : query; }; return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data; }]; //配合nginx处理本地开发, 服务器调式的问题(接口是跨域的) $httpProvider.interceptors.push(function($q){ return { 'request':function(config){ if(config.url.indexOf('html') == -1){ config.url = "" + config.url; } return config || $q.when(config); } } }); //注销RootScope上面的广播事件 //var deregister = $rootScope.$on("rootEvent", function(event,data) { // //}); // //$scope.$on('$destory', function() { // deregister(); // 退订事件 //}); //注册$onRootScope方法,并在执行完毕后直接销毁, 防止内存溢出 $provide.decorator('$rootScope',['$delegate',function($delegate){ Object.defineProperty($delegate.constructor.prototype,'$onRootScope',{ value:function(name,listener){ var unsubscribe = $delegate.$on(name,listener); this.$on('$destroy',unsubscribe); }, enumerable:false }); return $delegate; }]) //使用,不需要手动去销毁这个事件 //$scope.$onRootScope("key",function(){ // console.log("get key"); //}) //$rootScope.$broadcast("key",{name:1}); }); app.factory('timestampMarker', [function() { return { request: function(config) { config.requestTimestamp = new Date().getTime(); return config; }, response: function(response) { response.config.responseTimestamp = new Date().getTime(); return response; } }; }]); app.config(['$httpProvider', function($httpProvider) { $httpProvider.interceptors.push('timestampMarker'); }]); //$http.get('xxxx').then(function(response) { // var time = response.config.responseTimestamp - response.config.requestTimestamp; // console.log('The request took ' + (time / 1000) + ' seconds.'); //}); //当路由变化的时候触发 app.run(function($rootScope,$templateCache) { $rootScope.isLogin = true; $rootScope.loginStyle = ""; $rootScope.$on('$stateChangeStart', function (event, current, previous) { if(current.name != "login" && $rootScope.currentState != current.name){ // console.log($rootScope.currentState); $rootScope.currentState = current.name; } //清理所有template缓存 if (typeof(current) !== 'undefined'){ $templateCache.removeAll(); } $rootScope.currentName = current.name; if($rootScope.currentName == "login"){ $rootScope.isLogin = false; $rootScope.loginStyle = "login"; $rootScope.col = ""; }else{ $rootScope.isLogin = true; $rootScope.loginStyle = ""; } }); });代码审计一下
最新发布
08-23
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值