Reputation: 1591
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);
}]
}});
Upvotes: 2
Views: 1023
Reputation: 4611
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;
}],
}});
Upvotes: 4
Reputation: 3437
I think your best option in this case is not exactly promise chaining, more promise nesting. This changes the output, but not significantly:
$routeProvider.when('/report/:ruleId', { resolve: {
bothVars: ['$route', '$service', function ($route, $service) {
return $service.getRequest().
then(function(response1) {
return $service.getAnotherRequest(response1.data.id).
then(function(response2) {
return {
var1: response1.data,
var2: response2.data
};
});
});
]
}});
This can get a little wild if you nest too deeply, but I think this is fine. I don't love this solution, but it's the best I've found for this particular problem. One final note: don't preface your own services with '$'. Angular uses that convention for it's own services to avoid conflicts.
Upvotes: 1