I have an AngularJS application where I need some basic information, that I get from the server via async call, before I can continue loading or processing the page.
I know there are other similar questions to this, but all of the others I found are related to loading a data before initializing an specific part (directive, controller, factory, etc..).
What I want is to use this data in multiple places, doesn't matter if it's a component, directive, etc. Because If I initialize in one of them without the data, I will not be able to proceed.
For example: I have a div in my footer
where I show a location using Google Maps, so I need the location before I can run (currently inside a directive) the code to place the Google Maps. I made a plunker to illustrate this problem (without the fix mentioned below).
https://plnkr.co/edit/2RkansVp3NQNx3Tb4lMD?p=preview
What I did
I could solve this problem by using ui-router resolve, although it doesn't seem to be the proper way to do this. I'm using a "blank" state just to resolve the data and moved the basic elements from the index.html to this app.html page, which would be my index, but since I need to load the data, I had to move.
This is my code:
.state('app', {
abstract: true,
views: {
'main': {
templateUrl: 'view/app.html'
}
},
resolve: {
dataLoad: function($q, api, store) {
var promises = {
//[..loading more data..]
location: api.request('getLocation')
}
return $q.all(promises).then(function(resolve){
//[..resolving more data..]
return store.location = resolve.location;
})
}
}
})
.state('home', {
parent: 'app',
url: '/Home',
views: {
'app': {
templateUrl: 'view/home.html'
}
}
})
index.html
<body ui-view="main"></body>
app.html
<header>[...]</header>
<main ui-view="app"></main>
<footer>[...]</footer>
This way I can initiate all the data properly, since the app.html will load only after the resolve on the parent app state.
But, as you can see, my index.html is completely empty and I had to create the app.html just to go around this situation.
Is this the way to go? Or is there a better/correct method to load the data before I initiate my application, or to load in other area (.run
, for example) and wait until all the data is resolved?