0

I have a number of services defined within an AngularJs application. There is a root service that must load, get some data from a server, then the other services that depend on this root service can initialise, and after that the controllers can load and display data on the page.

Th problem is controllers are loading before the root service, and child services, can fully initialise, eg:

  • User loads page
    • root service starts initialisation
    • controller loads, which depends on child service (which depends on root service)
    • page binding fails because child service cannot supply data to controller
    • root service finishes intialisation (too late)

The initialisation flow I want is this:

  • User loads page
    • root service starts initialisation
    • root service finishes intialisation
    • child services which depend on root service initialise
    • controller loads, which depends on child service
    • page binding succeeds

Is there a technique for handling this kind of problem?

glasswall
  • 127
  • 1
  • 10
  • But your controller models should be ok once services is done and you reassign values to your controllers scopes, yes? – Ahmad Sep 03 '14 at 11:28
  • 1
    Maybe this help you http://stackoverflow.com/questions/16286605/initialize-angularjs-service-with-asynchronous-data to load something async you must use promises or callback functions – falloff Sep 03 '14 at 12:03

1 Answers1

1

From Angular docs https://docs.angularjs.org/guide/module

A module is a collection of configuration and run blocks which get applied to the application during the bootstrap process. In its simplest form the module consist of collection of two kinds of blocks:

Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.

Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

angular.module('myModule', []).
  config(function(injectables) { // provider-injector
    // This is an example of config block.
    // You can have as many of these as you want.
    // You can only inject Providers (not instances)
    // into config blocks.
  }).
  run(function(injectables) { // instance-injector
    // This is an example of a run block.
    // You can have as many of these as you want.
    // You can only inject instances (not Providers)
    // into run blocks
  });

Try this.

Community
  • 1
  • 1
walts
  • 92
  • 3
  • 15