Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs suitable moment to launch a http request when app start

Tags:

angularjs

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?

like image 432
Miaonster Avatar asked Jul 08 '13 14:07

Miaonster


People also ask

Which object does the http GET () function return?

response : interceptors get called with http response object. The function is free to modify the response object or create a new one. The function needs to return the response object directly, or as a promise containing the response or a new response object.


1 Answers

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.

like image 63
holographic-principle Avatar answered Dec 08 '22 03:12

holographic-principle