Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for $http result before initializing angular app

I have an angular app that needs to do a quick http request to get some config information before the rest of the application is initiated, at least before the controllers. Looked into using $UrlRouterProvider, but I did not figure out how to make the app wait for the http be done.

What I need to be finished:

 $http({method: 'GET', url: '/config'}).then(function(res) {
      configProvider.setConfig(res.data.config);
 }
like image 568
Slagathor Avatar asked Nov 16 '17 11:11

Slagathor


1 Answers

You can create a separate js file where you can make http request and then initialize/bootstrap your app via js code instead of ng-app in html code.

Refer the below code:

(function() {
  var application, bootstrapApplication, fetchData;
  application = angular.module('app');
  fetchData = function() {
    var $http, initInjector;
    initInjector = angular.injector(['ng']);
    $http = initInjector.get('$http');
    $http.get('<url>');
  };
  bootstrapApplication = function() {
    angular.element(document).ready(function() {
      angular.bootstrap(document, ['app']);
    });
  };
  fetchData().then(bootstrapApplication);
})();

I hope it helps.

like image 124
Harpreet Avatar answered Sep 28 '22 00:09

Harpreet