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!

有帮助吗?

解决方案

There's no way these would be undefined, unless they were already undefined in the run block. However I've seen cases where the debugging tool thinks some variables are undefined when they actually aren't. That happened to me in FireBug with an old FF version.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top