konr
konr

Reputation: 2565

Configuring a factory inside a service

I have a service auth with a function login, which logs in to a server and saves an authorization token to a variable:

myApp.factory 'auth', ['$http', ($http) ->
    @token = null
    @login = (user, pass) ->

    ...

]

After logging in, I update $http's factory to use the defined token in the header of each request.

myApp.factory 'httpAuthInterceptor', ($injector, $q) ->
  request: (request) ->
    token = ($injector.get 'auth').token
    request.headers.Authorization = "Bearer " + token
  return request or $q.when request

The problem is that the interceptors are configured in the top-level at startup:

myApp.config ($httpProvider) ->
  $httpProvider.interceptors.push 'httpAuthInterceptor'

How can I reconfigure them after the login function, or as its last step?

Thanks!

Upvotes: 1

Views: 231

Answers (1)

eddiec
eddiec

Reputation: 7646

You don't need to modify the interceptor, once the authentication has completed you should set application wide headers in your auth factory with the below:

$http.defaults.headers.common['Authorization'] = "Bearer " + token;

Upvotes: 1

Related Questions