我已经对URL进行了HTTP post API调用。
我得到了回复,但我很困惑如何编写成功函数,因为它有很多种方法。
这是我的API调用。请帮助我,成功函数将如何?<
var req = {
method: 'POST',
url: viewProfileurl,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + $rootScope.token,
},
params: {
'action':'view'
}
}
$http(req);
答案 0 :(得分:2)
Angular在$http
实施中内部使用承诺,即$q
:
一种帮助您异步运行函数并使用它们的服务 完成处理后返回值(或例外)。
所以,有两种选择:
您可以使用.success
和.error
回调:
var req = {
method: 'POST',
url: viewProfileurl,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + $rootScope.token,
},
params: {
'action': 'view'
}
}
$http(req).success(function() {
// do on response success
}).error(function() {
});
但是.success
&amp; {/ 1}}已被弃用。
所以,请选择第二个选项。
使用.error
功能
.then
答案 1 :(得分:2)
您需要编写成功回调以检索API返回的数据。
$http(req)
.then(function (response) {
var data = resposne.data;
...
}, function (error) {
var errorStatusCode = error.StatusCode;
var errorStatus = error.Status;
...
});
基本上$ http会返回一个promise,你需要编写一个回调函数。
或者你可以这样做:
$http(req).success(function(respData) { var data = respData; ... });
$http(req).error(function(err) { ... });
答案 2 :(得分:2)
成功与错误语法
$http.get("/api/my/name")
.success(function(name) {
console.log("Your name is: " + name);
})
.error(function(response, status) {
console.log("The request failed with response " + response + " and status code " + status);
};
使用然后
$http.get("/api/my/name")
.then(function(response) {
console.log("Your name is: " + response.data);
}, function(result) {
console.log("The request failed: " + result);
};
答案 3 :(得分:1)
$http
会返回一个可以使用then
函数的承诺。
$http(req).then(function (data) { ...; });
then
的定义:
then(successCallback, failCallback)