Search code examples
javascriptangularjsangular-ui-routerangular-resource

In angularjs using ui-router, how can I access the ngResource error within $stateChangeError when a request fails in the resolve part of a state?


Here is a plunker with my problem: http://plnkr.co/edit/vdctsTcMq4nD1xpUl3pu

Essentially, the $resource promise is rejected because the request fails (with a 404). I know I can access the error within the resolve by simply doing something like

AppFactory.get(null, function(error) {
    console.log(error);
})

However I would like to write my generic resolve error handling code in one place - in my listener for $stateChangeError. I know that there is an error object passed on this event, however, the error object seems to be empty. How can I get the ngResource error into the $stateChangeEvent error object?


Solution

  • It turns out I had the right idea on how to do this - I just had missed a parameter in my listener (the fromState parameter) and the error object was empty because it was actually the fromState object. Other than this, nothing else had to be changed in my code and everything started working. In case anybody else ever needs an example of how to do this, here is a working plunker with my silly mistake fixed: http://plnkr.co/edit/ubOTnw0TuWqzKky2WqxH