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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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: stackoverflow.com/questions/16286605/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.