gpt4 book ai didi

javascript - AngularJS 服务返回状态

转载 作者:行者123 更新时间:2023-11-27 23:42:37 24 4
gpt4 key购买 nike

我正在做自定义 $http 服务,看起来像这样:

angular.factory('myHttp', function($http){
var obj = {};

obj.get = function(path) {
return $http.get(path).then(function(result){
return result;
},function(result){
console.log("result error:"+path);
return result;
});
}

然后,可以像这样使用该服务:

    myHttp.get($scope.url).
then(function(response) {
console.log("It's success");
$scope.status = response.status;
$scope.data = response.data;
}, function(response) {
console.log("It's fail");
$scope.data = response.data || "Request failed";
$scope.status = response.status;
});

它确实会返回成功和失败的结果。不过,即使失败了,也会在成功部分返回。这意味着,如果连接失败,我仍然会在控制台中看到It's success

当连接失败时,如何使其返回失败部分?

最佳答案

您正在使用then链接,这表示除非第一个 then 处理程序方法返回一个 promise 对象,否则将调用第二个调用成功处理程序。

This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback (unless that value is a promise, in which case it is resolved with the value which is resolved in that promise using promise chaining). It also notifies via the return value of the notifyCallback method. The promise cannot be resolved or rejected from the notifyCallback method.

由于在您的情况下,您从第一个处理程序返回 result 对象,因此 then 方法返回的 promise 被视为已解决,因此第二个处理程序的成功处理程序然后被调用。

您可以使用如下的成功/错误处理程序来修复它

obj.get = function (path) {
return $http.get(path).error(function (result) {
console.log("result error:" + path);
});
}

关于javascript - AngularJS 服务返回状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33536324/

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