2015-11-05 44 views
1

我做定制$http服务,是这个样子:AngularJS服务回报状态

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

连接失败时,如何使它在失败部分返回?

回答

1

您正在使用then链接,其中说,除非第一个然后处理程序方法返回一个承诺对象第二个调用成功处理程序将被调用。

该方法返回一个新的承诺,其解决或者经由 的successCallback,errorCallback(的返回值被拒绝,除非该 值是一个承诺,在这种情况下,它与哪个 在解析值解析承诺使用承诺链)。它还通过notifyCallback方法的返回值通知 。该承诺不能通过notifyCallback方法解决或拒绝 。

由于你的情况,你是从第一个处理程序返回result对象,由then方法返回的承诺被认为是解决,这样第二then的成功处理程序被调用。

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

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

非常感谢您的回答。您的解决方案适用于返回错误。但是,如果我希望在输出失败前多次重试失败连接,那么如何完成?这似乎不适用于您的解决方案。 – user1995781

0

我已经写了两个办法让mehtod调用和处理错误

** 1。 $ HTTP函数已经返回无极对象本身

//factory method 
obj.get = function (path) { 
    return $http.get(path).then(function (results) { 
     return results.data; 
    }); 
}; 

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


2. The Verbose Way 
obj.get = function (path) { 
    var def = $q.defer(); 
    $http.get(path).success(function (data) { 
     def.resolve(data); 
    }).error(function() { 
     def.reject("Failed to get"); 
    }); 
    return def.promise; 
}; 

//call from controller 
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; 
}); 

这里是链接,清晰的认识$http

+0

感谢您的回答。但是您的工厂方法不会捕获失败连接。这意味着我想要成功,并且在回传给控制器之前无法通过工厂进行一些处理。 – user1995781

+0

使用The Verbose Way或将.error(函数(响应)方法应用到工厂 – Shohel

+0

试图用你的详细方式。它可以工作,但是成功或失败,没有数据传递。 – user1995781