AngularJS失败的资源GET

时间:2012-07-22 06:05:00

标签: javascript json angularjs

有谁知道如何检查AngularJS中是否无法获取资源?

例如:

//this is valid syntax
$scope.word = Word.get({ id : $routeParams.id },function() {
    //this is valid, but won't be fired if the HTTP response is 404 or any other http-error code
});

//this is something along the lines of what I want to have 
//(NOTE THAT THIS IS INVALID AND DOESN'T EXIST)
$scope.word = Word.get({ id : $routeParams.id },{
    success : function() {
      //good
    },
    failure : function() {
      //404 or bad
    }
});

有什么想法吗?

3 个答案:

答案 0 :(得分:49)

在出现错误时,应在第一个回调函数后触发另一个回调函数。取自docs和群组post

$scope.word = Word.get({ id : $routeParams.id }, function() {
    //good code
}, function(response) {
    //404 or bad
    if(response.status === 404) {
    }
});
  
      
  • HTTP GET“class”操作:Resource.action([parameters],[success],[error])
  •   
  • 非GET“类”操作:Resource.action([parameters],postData,[success],[error])
  •   
  • 非GET实例操作:实例。$ action([参数],[成功],[错误])
  •   

答案 1 :(得分:5)

也回答@Adio的问题。

当任何http响应代码被AngularJS视为错误时,将调用第二个回调(仅[200,300]中的响应代码被视为成功代码)。因此,您可以拥有一般错误处理功能,而不关心特定错误。 可以使用if语句根据错误代码执行不同的操作,但这不是强制性的。

答案 2 :(得分:0)

这只是为了通知。

从角度1.6.x开始,不推荐成功和失败。所以,现在请关注当时并代表成功和失败。

所以,上面的代码看起来像角1.6.x如下:

$scope.word = Word.get({ id : $routeParams.id }).then(=> () {
    //this is valid, but won't be fired if the HTTP response is 404 or any  other http-error code
}).catch(=> () {
    // error related code goes here
});