我有这样的代码:
app.controller('MainCtrl', function ($scope, $http){
$http.get('api/url-api')
.success(function (data, status, headers, config){
}
}
在我的本地环境中,工作正常,但在服务器中,返回以下错误:
TypeError:$http.get(...).success不是函数
有什么想法吗?谢谢
发布于 2016-12-16 00:56:10
.success
语法在Angular v1.4.3之前是正确的。
对于直到Angular v.1.6的版本,你必须使用then
方法。then()
方法有两个参数:一个success
和一个error
回调,这两个回调将通过响应对象调用。
使用then()
方法,将callback
函数附加到返回的promise
。
如下所示:
app.controller('MainCtrl', function ($scope, $http){
$http({
method: 'GET',
url: 'api/url-api'
}).then(function (response){
},function (error){
});
}
请参阅参考here.
Shortcut
方法也是可用的。
$http.get('api/url-api').then(successCallback, errorCallback);
function successCallback(response){
//success code
}
function errorCallback(error){
//error code
}
您从响应中获得的数据应为JSON
格式。JSON是一种很好的传输data的方法,而且在AngularJS中很容易使用。
两者之间的主要区别是.then()
调用返回一个promise
(由callback
返回的值解析),而.success()
是更传统的注册callbacks
的方式,不返回promise
。
发布于 2017-05-05 05:22:30
这可能是多余的,但上面投票最多的答案,.then(function (success)
说,这对我来说不适用于Angular版本的1.5.8
。取而代之的是使用response
,然后在块中,response.data
为我获得了我正在寻找的json数据。
$http({
method: 'get',
url: 'data/data.json'
}).then(function (response) {
console.log(response, 'res');
data = response.data;
},function (error){
console.log(error, 'can not get data.');
});
发布于 2017-10-21 23:02:43
如果你正在尝试使用AngularJs 1.6.6,从2017.21/10/2017开始,以下参数将作为.success工作,但已经耗尽。.then()方法有两个参数:响应和错误回调,它们将通过响应对象调用。
$scope.login = function () {
$scope.btntext = "Please wait...!";
$http({
method: "POST",
url: '/Home/userlogin', // link UserLogin with HomeController
data: $scope.user
}).then(function (response) {
console.log("Result value is : " + parseInt(response));
data = response.data;
$scope.btntext = 'Login';
if (data == 1) {
window.location.href = '/Home/dashboard';
}
else {
alert(data);
}
}, function (error) {
alert("Failed Login");
});
上面的代码片段适用于登录页面。
https://stackoverflow.com/questions/41169385
复制相似问题