No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.
General Tech 10 Answers
General Tech 7 Answers
General Tech 3 Answers
General Tech 9 Answers
manpreet
Best Answer
2 years ago
I have an AngularJS service that I want to initialize with some asynchronous data. Something like this:
Obviously this won't work because if something tries to call
doStuff()
beforemyData
gets back I will get a null pointer exception. As far as I can tell from reading some of the other questions asked hereand here I have a few options, but none of them seem very clean (perhaps I am missing something):Setup Service with "run"
When setting up my app do this:
Then my service would look like this:
This works some of the time but if the asynchronous data happens to take longer than it takes for everything to get initialized I get a null pointer exception when I call
doStuff()
Use promise objects
This would probably work. The only downside it everywhere I call MyService I will have to know that doStuff() returns a promise and all the code will have to us
then
to interact with the promise. I would rather just wait until myData is back before loading the my application.Manual Bootstrap
Global Javascript Var I could send my JSON directly to a global Javascript variable:
HTML:
data.js:
Then it would be available when initializing
MyService
: