6

I just started to learn Angularjs 2 days ago. A question have confused me for all the 2 days.

I need to make a http request to the server to get some data when the app start, but I cannot find the suitable moment to do this.

I've tried to make a controller, which calls $http.get(). But It doesn't work. It seems that the controller won't be instantiated if it's never used in the html (not sure about this).

I also tried to find other ways, but I only found $http which is used for http request. And $http only appears in the controller.

Maybe I need use other Angularjs methods? Or, I should do the instantiate action manually?

Miaonster
  • 1,482
  • 2
  • 18
  • 32
  • Similar to question: https://stackoverflow.com/questions/16286605/angularjs-initialize-service-with-asynchronous-data – 0x6adb015 Aug 03 '17 at 17:55

1 Answers1

6

Something like:

angular.module('yourApp').run(['$rootScope', '$http', function ($rootScope, $http) {
  // do stuff here
}]);

From the documentation:

Run Blocks

Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.

holographic-principle
  • 19,688
  • 10
  • 46
  • 62
  • 4
    I think it'd be good to mention that the startup of the application won't be blocked. it's quite likely that the poster wants to use the data right after the application started. This is a good starting point: http://stackoverflow.com/questions/16286605/initialize-angularjs-service-with-asynchronous-data – Eduard Gamonal Jul 08 '13 at 14:49