4

In my application, I'm getting some data in app.run using $http.get() The result from this is required to proceed to the controller. Currently my controller is executing before the completion of this $http.get How can I make my controller's execute after the execution of $http.get()

app.run(function ($rootScope, $http, $cookies) {
var currentLanguageId = angular.fromJson($cookies.get('mykey')).UserInfo.Country;

    $http.get('myurl').then(function (serviceInfo) {


        $rootScope.serviceURL = serviceInfo.data.serviceURL;

    }, function (error) {
        alert('error service info');
    });
Jojo
  • 403
  • 5
  • 16

4 Answers4

1

run can't handle asynchronous work at the moment. See this issue : https://github.com/angular/angular.js/issues/4003

You have multiple solutions for that. You can get your data without Angular and start Angular manually ( How to wait for a promise in a Run block in Angular? )

Or you can use the resolve of your route to do this : AngularJS : Initialize service with asynchronous data

Community
  • 1
  • 1
Magus
  • 14,796
  • 3
  • 36
  • 51
0

You can use angular scope event. When data is fetched, you can broadcast an event from $rootScope to all controllers and receive this event in target controller.

gzc
  • 8,180
  • 8
  • 42
  • 62
0

You may use $rootScope.$broadcast();in the app.run and then use $rootScope.$on() in your controller.

app.run(function ($rootScope, $http, $cookies) {
    var currentLanguageId = angular.fromJson($cookies.get('mykey')).UserInfo.Country;
    $http.get('myurl').then(function (serviceInfo) {
        $rootScope.serviceURL = serviceInfo.data.serviceURL;
        $rootScope.$broadcast('serviceInfoReceived')
    }, function (error) {
        alert('error service info');
    });
});

In your Controller

app.controller ('myCtrl' , function($rootScope) {
    $rootScope.$on("serviceInfoReceived", function(){
         console.log($rootScope.serviceURL)
    });
})

Hope this may help you.

0

This is an old question, however the $rootScope.$on solution will not always work. It will depend on the timing of the controller registering the listener. The way I have found that works is to set a $rootScope property, and then configure a recursive timeout to wait for it to be set.

function waitForRun() {
  if($rootScope.runFinalized){
    // do something
  } else {
    $timeout(waitForRun, 500)
  }
}
waitForRun();

and after the last .run block:

.run(function($rootScope) { $rootScope.runFinalized = true; })

Ugly, but it works.