AngularJS: Resolve in RouteProvider - detecting Success / Failure?

Martin picture Martin · Jul 19, 2013 · Viewed 10.7k times · Source

I have got a resolve working on my routeprovider but I just return the promise so i don't know if its success or failure. This is what I have

.when('/items', {
    templateUrl: 'views/items.html',
    controller: 'ItemsCtrl',
    resolve: {
        resolvedData: function(Restangular) {
            return Restangular.one('Items').get();
        }
    }
})

Now this does work but how do I detect success or failure. I could enter this in the resolve method, but what would I return in the success and failure. Remembering I need to have the item injected in my controller.

.when('/items', {
    templateUrl: 'views/items.html',
    controller: 'ItemsCtrl',
    resolve: {
        resolvedData: function(Restangular) {
            Restangular.one('Items').get().then(function(data) {
                // success
            }, function() {
                // failure
            });
        }
    }
})

I did see an example here but I am confused if this is what I need and how to use it?

AngularJS - rejected $http promise with $routeProvider:resolve

It seems to be returning a manual promise.

resolve: {
    response: ['Warranty'
        '$q',
        function(Warranty, $q) {
            var dfd = $q.defer();
            Warranty.sendRequest().then(function(result) {
                dfd.resolve({
                    success: true,
                    result: result
                });
            }, function(error) {
                dfd.resolve({
                    success: false,
                    reason: error
                });
            });
            return dfd.promise;
        }
    ]
}

What I really want to do is in my controller have the resolved variable injected into the controller, if it fails then I would also like to have access to the failure in the controller so I can display to the user that it wasn't possible to render due to an issue.

Answer

Ye Liu picture Ye Liu · Jul 19, 2013

You can just return the return value of the then method:

resolve: {
    resolvedData: function(Restangular){
        return Restangular.one('Items').get().then(function (data) {
            ...
            return successData; // resolvedData will be resolved with the successData
            }, function () {
            ...
            return failureData; // resolvedData will be resolved with the failureData
            });
    }
}

The then method doc:

This method returns a new promise which is resolved or rejected via the return value of the successCallback or errorCallback.