Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize AngularJS Constant using $http.get call response

How can I initialize my angularjs app contant with reponse of a GET request.

For example :-

    angular.module('A',[]);
    angular.module('A').run( function ($rootScope,$http){
      $rootScope.safeApply = function (fn) {

                $http.get('url').success(function(result){

                    // This doesn't work. I am not able to inject 'theConstant' elsewhere in my application
                    angular.module('A').constant('theConstant', result);
                });                   
                var phase = $rootScope.$$phase;
                if (phase === '$apply' || phase === '$digest') {
                    if (fn && (typeof (fn) === 'function')) {
                        fn();
                    }
                } else {
                    this.$apply(fn);
                }
            };
      });

I want to set the constant while my app get initialized and be able to share the constant across my components.

What's is the best approach to accomplish this?

like image 286
Kumar Sambhav Avatar asked Nov 07 '14 14:11

Kumar Sambhav


1 Answers

As explained in this blog post, you can init a constant before bootstrapping your app:

(function() {
    var app = angular.module("A", []);

    var initInjector = angular.injector(["ng"]);
    var $http = initInjector.get("$http");

    return $http.get("/path/to/data.json")
        .then(function(response) {
            app.constant("myData", response.data);
        })
        .then(function bootstrapApplication() {
            angular.element(document).ready(function() {
                angular.bootstrap(document, ["A"]);
            });
        });


}());
like image 151
Benoît Guérout Avatar answered Sep 23 '22 14:09

Benoît Guérout