3

I'm working on an angular application and I'm using a service which should load some details from the server before the execution of the application is continued.

application.run(($myService)=>{
    myService.loadSomething() //The application should pause until the execution  of the Service
                              //is completed until this the browser shoudl stay in a "loading state"
});

Is sometehing like this even possible?

Ced
  • 1,301
  • 11
  • 30

3 Answers3

8

Not in the .run - the .run function will not "block". Typically, one can use ngRoute/ui-router and use the resolve property.

If you don't want to go this route, you could create an app-level controller and "resolve" there:

.controller("AppCtrl", function($scope, loaderSvc){
   $scope.load = false;
   loaderSvc.preload().then(function(){
      $scope.load = true;
   });
});

and in the View:

<div ng-controller="AppCtrl">
  <div ng-if="::load" ng-include="'main.html'">
</div>
New Dev
  • 48,427
  • 12
  • 87
  • 129
  • One question, I'm new to angular as well. What does the `::` in `::load` means? Thanks – trinaldi Sep 19 '16 at 11:01
  • 1
    @Tico one way binding https://blog.thoughtram.io/angularjs/2014/10/14/exploring-angular-1.3-one-time-bindings.html – Azadrum May 24 '17 at 07:20
  • 1
    It's one-time, not one way. One-time bindings are calculated/rendered only once, which means its values can not be modified after first render. One way bindings can be calculated/rendered multiple times, but values can be modified from one direction only. – Timo Jan 16 '19 at 12:51
5

Get yourself familiar with $q and try to plan your application as it must not wait for anything to happen. Asynchronism is the key of every AngularJS app.

If you are using the router, get familiar with resolve, that may also help you "waiting" for data before a route/view will be shown.

Basster
  • 310
  • 1
  • 10
3

I had a similar requirement and I ended up using angular-deferred-bootstrap by @philippd.

For a detailed question and thought provoking discussion plz check AngularJS : Initialize service with asynchronous data

Community
  • 1
  • 1
Vivek Athalye
  • 2,974
  • 2
  • 23
  • 32