I am trying to execute some initialization code in a parent state of the Angular ui-router. The initialization code is orderService.getStoreInfo()
which returns a promise. Only when this promise is resolved, do I want to trigger the child state. However, what I am noticing is that the child state is triggered even before the parent's promise has resolved. What am I doing wrong? Here' my code:
function configure($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
abstract: true,
template: '<ui-view/>',
resolve: {
storeInfo: /* @ngInject */ function(orderService) {
console.log('home: resolve - orderService.getStoreInfo()');
return orderService.getStoreInfo();
}
}
})
.state('home.orders', {
url: '^/',
template: '<my-order-list data-orders="vm.orders"></my-order-list>',
resolve: {
orders: /* @ngInject */ function (orderService) {
console.log('home.orders: resolve - orderService.getOrders()');
return orderService.getOrders();
}
},
controller: ['orders', function (orders) {
this.orders = orders;
}],
controllerAs: 'vm',
});
}
The console log is as follows:
home: resolve - orderService.getStoreInfo()
home.orders: resolve - orderService.getOrders()
... messages from orderService.getStoreInfo() ...
This clearly shows that the child state is firing even before the parent state has been resolved.
The answer is here: the resolve
keys MUST be injected into the child states if you want to wait for the promises to be resolved before instantiating the children. So just explicitly inject storeInfo
into a resolve function of the child state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With