I'm attempting to handle http errors within AngularJS (using ui-router), but am losing the context of my run function in the following code.
bugtracker.run(['$rootScope', '$state', function($rootScope, $state) {
//at this point $state and $rootScope are defined
$rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {
//at this point $state and $rootScope are undefined
});
}]);
The code that causes $stateChangeError to trigger is as follows.
//main.js
bugtracker.config(['$stateProvider', '$httpProvider', '$compileProvider', function($stateProvider, $httpProvider, $compileProvider) {
//...
$stateProvider.state('projects.show', {
url: '/{projectId:[0-9]{1,8}}',
templateUrl: '/assets/projects/show.html',
controller: 'ProjectShowCtrl',
resolve: bugtracker.controller('ProjectShowCtrl').resolve
});
//...
}]);
//ProjectShowCtrl.js
projectShowCtrl.resolve = {
project: function(Project, $q, $stateParams, $state) {
var deferred = $q.defer();
Project.findById($stateParams.projectId, function(successData) {
deferred.resolve(successData);
}, function(errorData) {
deferred.reject(errorData); // you could optionally pass error data here
});
return deferred.promise;
},
delay: function($q, $timeout) {
var delay = $q.defer();
$timeout(delay.resolve, 1000);
return delay.promise;
}
};
I would like $state to be defined within the anonymous function called by the $on function so that I could redirect the user to a 401, 403, etc. page, but I'm unsure why it is not. In other examples I have seen (https://github.com/angular-ui/ui-router/issues/898) it is implied that $state is defined within the context of the anonymous function.
If anyone could explain why $state is not defined or what I can change to make it defined I would greatly appreciate it!
this
within the anonymous function iswindow
. This may be normal; however, I would have expected it to be$rootScope
. – Scott Mielcarski May 11 at 1:06$state.transitionTo('error.401')
) and it worked! I can't believe it, thank you! – Scott Mielcarski May 11 at 1:08$rootScope
would have beenthis
only if the library was designed that way. – plalx May 11 at 1:25