Wait for $http result before initializing angular app

Viewed 250

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);
 }
2 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.

Resolve must be declared on state, not on the view

change

.state('app', {
    abstract: true,
    url:'/',
    views: {
        "content": {
            templateUrl: "myurl.html"
        },
        resolve {
            myVar: ['$http', 'myService', function($http, myService) {
                   return $http({method: 'GET', url:'url'})
                            .then(function(res) { //do stuff })

to

.state('app', {
    abstract: true,
    url:'/',
    views: {
        "content": {
            templateUrl: "myurl.html"
        }
    },
    resolve {
            myVar: ['$http', 'myService', function($http, myService) {
                   return $http({method: 'GET', url:'url'})
                            .then(function(res) { //do stuff })...
Related