gpt4 book ai didi

angularjs - 如何从 Controller 知道 http.post().then... 是否成功?

转载 作者:行者123 更新时间:2023-12-01 09:21:08 24 4
gpt4 key购买 nike

我有一个 Controller ,它使用以下行通过名为 SendDataFactory 的工厂将数据发布到服务器:

SendDataFactory.sendToWebService(dataToSend)

而我的工厂 SendDataFactory 看起来像这样:

angular
.module('az-app')
.factory('SendDataFactory', function ($http, $q) {

var SendData = {};

/**
* Sends data to server and
*/
SendData.sendToWebService = function (dataToSend) {

var url = "example.com/url-to-post";
var deferred = $q.defer();

$http.post(url, dataToSend)

//SUCCESS: this callback will be called asynchronously when the response is available
.then(function (response) {
console.log("Successful: response from submitting data to server was: " + response);

deferred.resolve({
data: data
});
},

//ERROR: called asynchronously if an error occurs or server returns response with an error status.
function (response) {
console.log("Error: response from submitting data to server was: " + response);

deferred.resolve({
data: data
});
}
);

return deferred.promise;
}

return SendData;
});

我在这里和互联网上看到了一些例子

$http.post().success...

但我想用

$http.post().then...

自从 angular documentation says :

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.

我需要什么:

现在在我的 Controller 中,我需要检查 $http.post().then... 是否成功,然后根据成功或失败执行某些操作。我怎样才能做到这一点?

最佳答案

我想这就是你的意思:

$http.post(url, dataToSend)

//SUCCESS: this callback will be called asynchronously when the response is available
.then(function (response) {
console.log("Successful: response from submitting data to server was: " + response);

deferred.resolve({
data: response //RETURNING RESPONSE SINCE `DATA` IS NOT DEFINED
});
},

//ERROR: called asynchronously if an error occurs or server returns response with an error status.
function (response) {
console.log("Error: response from submitting data to server was: " + response);

//USING THE PROMISE REJECT FUNC TO CATCH ERRORS
deferred.reject({
data: response //RETURNING RESPONSE SINCE `DATA` IS NOT DEFINED
});

}
);

return deferred.promise;
}

您现在可以在 Controller 中使用:

SendDataFactory.sendToWebService(dataToSend)
.then(function(data) { /* do what you want */ })
.catch(function(err) { /* do what you want with the `err` */ });

关于angularjs - 如何从 Controller 知道 http.post().then... 是否成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32767905/

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