Restangular:如何读取cookie并在每个查询中添加到Headers [英] Restangular: How to read cookie and add to Headers at each query

查看:259
本文介绍了Restangular:如何读取cookie并在每个查询中添加到Headers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Cookie中读取令牌,并在每次查询时将其添加到标题中。

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

我试过这个:

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

它有效,但cookie只能读一次。在页面加载时。然后,如果cookie的值发生变化,它会保留第一个值而不是发送更新的值。

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.

我知道每次都能读取cookie吗?

Any idea how I can read the cookie each time?

推荐答案

您正在传递一个字符串,该字符串在执行代码时进行评估。它会永远不会改变你发现的。

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.

这篇关于Restangular:如何读取cookie并在每个查询中添加到Headers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆