Angularjs is the right time to run an http request when the application starts

I just started learning Angularjs 2 days ago. The question confused me for all two days.

I need to make an HTTP request to the server to get some data when the application starts, but I can not find the right moment for this.

I tried to make a controller that calls $http.get() . But that will not work. It seems that the controller will not be created if it has never been used in html (not sure about this).

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

Maybe I need other Angularjs methods? Or should I execute the instance action manually?

+6
source share
1 answer

Sort of:

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

From the documentation :

Run locks

The start blocks are closest to Angular to the main method. The launch block is the code that you need to run to run the application. It runs after you configure the entire service and create an injector. Launchers usually contain code that is difficult to test individually, and for this reason must be declared in isolated modules so that they can be ignored in unit tests.

+6
source

Source: https://habr.com/ru/post/948950/


All Articles