wesbos
wesbos

Reputation: 26317

AngularJS Module Configuration

Looking for some help with a best practice.

I have a module which I am setting a few custom headers. No big deal here:

  $httpProvider.defaults.headers.common['token'] = function() {
    return token;
  };

token is a value that I must $http.get() on the page load.

My intial thought was to put this in my controller, but after thinking about it, it more more sense to do it in the module configuration on page load where I am setting my custom headers:

var app = angular.module('app',['ngRoute', 'ngResource'],function($httpProvider) {
   // Custom headers
});

My question is two part:

  1. Is this the best way to do this?
  2. If it is, how do I make a $http.get() request inside of the module config?

Upvotes: 0

Views: 1733

Answers (1)

Erik Honn
Erik Honn

Reputation: 7576

app.config, as you might have noticed, won't allow you to use services like $http (or any service you make yourself), it's run before they are defined. Try putting the call in your app.run instead. It is after config and it has no restrictions against using services.

If it is the right approach or not is harder to answer as it depends on the exact use-case. As $http-calls are asynchronous you cannot just call your backend when the app starts and be sure the token exists in your controllers or services, the http call might not have returned yet! This might be a problem for you if you expect to use the token right away.

A better option, again depending on use-case, might be to use a resolve-function on any route that needs the token. A route will holds off on loading any controller and template until the routes resolve-function has finished. Using this method you can then be 100% sure that the token exists once the controller is run.

This video has a good intro to resolves.

They can also be combined. Running the http-call in your app.run, and then using a resolve function to make sure it exists before the controller loads.

Upvotes: 1

Related Questions