gpt4 book ai didi

AngularJS 的 Promise 成功函数

转载 作者:行者123 更新时间:2023-12-02 11:27:01 25 4
gpt4 key购买 nike

我已对 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);

最佳答案

Angular 在 $http 实现中内部使用 Promise,即 $q :

A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.

所以,有两个选择:

第一个选项

您可以使用 .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.error已被弃用。

所以,选择第二个选项。

第二个选项

使用 .then 函数代替

var req = {
method: 'POST',
url: viewProfileurl,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + $rootScope.token,
},
params: {
'action': 'view'
}

}

$http(req).then(function() {
// do on response success
}, function() {
// do on response failure
});

关于AngularJS 的 Promise 成功函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36640773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com