ngResource Dynamically Set Header on Each Request

2019-03-02 16:05发布

问题:

I see it isn't possible to edit headers with ngRessource after the service has been registered.

Isn't this a big problem for people using authentication via jwt tokens in the autorization header ?

I have to be able too set headers dynamically on each request :

  {     Authorization: 'Bearer '+ myAuthService.getToken()     }

It poses no problem what so ever with $http.

Is it really impossible to set tokens in the headers via ngRessource after the service has been registered ?

回答1:

I have to be able too set headers dynamically on each request :

To set the header on each request, make the header a function:

{ Authorization: function(config) {
                     return 'Bearer '+ myAuthService.getToken(); 
                 }
}

From the Docs:

  • headers – {Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. Functions accept a config object as an argument.

By furnishing a function, the header value will be computed on each request.