How to avoid the automatic $routeChangeError exception in the $routeProvider resolve function on a failed $http request?

209 views
Skip to first unread message

Rick Jolly

unread,
Apr 19, 2013, 7:32:47 PM4/19/13
to ang...@googlegroups.com
I'd like to use the resolve function to delay loading of a ng-view until I've retrieved data from the server. However, I'd like to display the view once the $http response is returned even if there is an error (for example, when the server sends a 401 or 500 header). Angular seems to assume we don't want to show the view in this case and broadcasts a $routeChangeError and logs an exception to the console. Is there a way to avoid that behavior? This seems to happen only in resolve, because it works if I put the $http code in MyCtrl. 

app.config(function ($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl : 'template.html',
            controller : MyCtrl,
            resolve : MyCtrl.resolve
        });
});

function MyCtrl($scope, data) {
    $scope.data = data;
}

MyCtrl.resolve = {
    response : function($http) {
        return $http({method: 'GET', url: 'http://example.com'}).
            success(function(data, status) {
                // This works and data is injected into MyCtrl
                return data;
            })
           .error(function(data, status) {
                // This doesn't work. Angular broadcasts $routeChangeError and logs an exception to the console 
                return 'error';
            });
    }
}

Rick Jolly

unread,
Apr 19, 2013, 8:24:33 PM4/19/13
to ang...@googlegroups.com
I've solved the issue by using the promise library with $http and calling resolve() in the $http error() function. I suppose $http was calling reject() behind the scenes? This does seem messy.

MyCtrl.resolve = {
    response : function($q, $http) {
       var deferred = $q.defer();

        $http({method: 'GET', url: 'http://example.com'})
            .success(function(data, status) {
                deferred.resolve(data);
            })
            .error(function(data, status){
                deferred.resolve("error");
            });

        return deferred.promise;
    }
}
Reply all
Reply to author
Forward
0 new messages