Joshua Leung Joshua Leung - 9 months ago 33
AngularJS Question

Where to make http request for every route in angularjs?

Suppose my web app needs to make a http request to get my site title, site description and so on. Since these variables are common to all pages, it makes sense to request those every time a user enter the site.

The question is, where do I make those calls? In run block? Or to create a root controller to do these tasks?


You can use one of these two approaches:

  1. Make your call in run block and store the value in $rootScope and use anywhere you want,
  2. In your states, use resolve to get the page title and details , and get it in the views , For ease use resolve in root state and use the resolved variable as a dependency in other child or sibling routes to get values..

        $stateProvider.state('root', {
            // Example using function with simple return value.        
            promiseObj:  function($http){
            // $http returns a promise for the url data
            return $http({method: 'GET', url: '/someUrl'});
          $scope.title = promiseObj.title;