0

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?
4
  • -1 not a question (see: "My question is that token is a value that I must $http.get() on the page load.") Commented Aug 27, 2013 at 14:46
  • See below that for the question. Please don't be a jerk,its an actual question. Commented Aug 27, 2013 at 14:48
  • I'm not being a jerk. See your question title; also not a question. Commented Aug 27, 2013 at 14:48
  • Questions are clearly stated: My question is two part: Is this the best way to do this? If it is, how do I make a $http.get() request inside of the module config? Commented Aug 27, 2013 at 14:50

1 Answer 1

1

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.

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

1 Comment

Thanks so much for taking the time to explain this, I really appreciate it :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.