-->

Restangular: How to read cookie and add to Headers

2019-08-05 03:39发布

问题:

I'm trying to read a token from a cookie and ad it to the headers at each query.

I tried this:

Restangular.setDefaultHeaders({ Authorization: "Token " + $cookieStore.get('token') })

It works, but the cookie only gets read once. At page load. Then if the value of the cookie changes, it keeps the first value instead of sending the updated value.

Any idea how I can read the cookie each time?

回答1:

You are passing a string, which is evaluated at the time the code is executed. It will never change as you have found out.

Instead you will need to pass a function, like this -

Restangular.setDefaultHeaders({ Authorization: function() { return "Token " + $cookieStore.get('token'); } })

Which will then be evaluated each time the value is actually used.