AngularJS Failed Resource GET

后端 未结 3 1825
离开以前
离开以前 2020-12-09 02:48

Does anyone know how you can check to see that a resource failed to be fetched in AngularJS?

For example:

//this is valid syntax
$scope.word = Word.g         


        
相关标签:
3条回答
  • 2020-12-09 03:12

    An additional callback function after your first callback function should fire when there is an error. Taken from the docs and group post:

    $scope.word = Word.get({ id : $routeParams.id }, function() {
        //good code
    }, function(response) {
        //404 or bad
        if(response.status === 404) {
        }
    });
    
    • HTTP GET "class" actions: Resource.action([parameters], [success], [error])
    • non-GET "class" actions: Resource.action([parameters], postData, [success], [error])
    • non-GET instance actions: instance.$action([parameters], [success], [error])
    0 讨论(0)
  • 2020-12-09 03:15

    This is just to inform.

    From angular 1.6.x, success and failure is deprecated. So please now follow the then and catch on behalf of success and failure.

    So, the above code look like in angular 1.6.x is as below:

    $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
    });
    
    0 讨论(0)
  • 2020-12-09 03:22

    Just to answer @Adio 's question too.

    The second callback will be called when any http response code is considered to be an error by AngularJS (only response codes in [200, 300] are considered success codes). So you can have a general error handling function and don't care about the specific error. The if statement there can be used to do different actions depending on the error code, but it's not mandatory.

    0 讨论(0)
提交回复
热议问题