burak emre burak emre - 1 month ago 6
AngularJS Question

Using promise chaining in resolve feature of $routeProvider

One of my variables in resolve method has dependency of another variable, is it possible to share same promise among variables in resolve method?

It seems $route.current.locals stores the resolved variables, however when var2 is processed, $route.current.locals is null since var1 is not resolved yet. What I'm trying to is something like this:

$routeProvider.when('/report/:ruleId', { resolve: {
var1: ['$route', 'service', function ($route, service) {
return service.getRequest();
}],
var2: ['$route', 'service', function ($route, service) {
return service.getAnotherRequest($route.current.locals.var1.id);
}]
}});

Answer

I hope this will work:

$routeProvider.when('/report/:ruleId', { resolve: {
    vars: ['$route', 'service','$q' function ($route, service) {
        var defer = $q.defer(),
        data = [];
        service.getRequest().then(function(firstResponse){
            data.push(firstResponse);
            service.getAnotherRequest(firstResponse.id).then(function(secondResponse){
                data.push(secondResponse);
                defer.resolve(data);
            });
        })

        return defer.promise;

    }],

}});