Mavlarn
Mavlarn

Reputation: 3883

How to initiate global data in angularjs

In my app, there is some data will be used by many views or controllers. You can think they are some data dictionary, like status map definition.

Now my solution is to get them in AppContoller, and put them into $scope or $ rootScope. (the $scope in AppController is the parent scope of all controllers, so the data is accessible in all controllers.)

But the problem is, it will be initiated with $resource asynchronously, so maybe they are not ready to be used. Because all data will be got with $resource. Sometime the other data is got before the necessary global data.

Now in the controllers using the global data, I have to check the global data, and if it is not ready, call the initializing function later with timeout.

So, my question is, is there a better solution to initialize the necessary data used by all app?

Upvotes: 0

Views: 871

Answers (1)

Manish Kr. Shukla
Manish Kr. Shukla

Reputation: 4477

Well, as far as i understand your problem, you need to ensure that when your app starts, you have some data fetched from server that can be used globally throughout your app.

My suggestion would be to go by the following approach,

  1. Create a service to hold your global data.

    var app = angular.module('myApp', []);
    
    app.service('constantService', function() {
    
        // All your constants declared here.
    
    
    });
    
  2. Now in your app.run method, make an ajax call or whatever you want to do, and initialize all the constants inside the service.

    app.run(function($rootScope, $http, constantService) {
    
        /*
    
            Make an ajax call here and fetch all the Constants from your server.
    
    
            var request = {};
            request.method = 'POST';
            request.data = {};
            request.url = url;
    
            var promise = $http(request);
            var service = this;
    
            promise.success(function(data, status, header, config) {
                if (showLoader === true || showLoader === undefined) {
                    service.hideModal();
                }
                successCallback(data);
            });
    
            promise.error(function(data, status, header, config) {
    
            });
    
    
        */
    
    });
    

You can show a loading message while these constants are being loaded, to avoid user intervention during the call.

Upvotes: 3

Related Questions