Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Failed Resource GET

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.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     } }); 

Any ideas?

like image 592
matsko Avatar asked Jul 22 '12 06:07

matsko


Video Answer


2 Answers

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])
like image 151
Gloopy Avatar answered Oct 08 '22 23:10

Gloopy


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.

like image 27
Rodrigo Chiong Avatar answered Oct 09 '22 01:10

Rodrigo Chiong