如何让 Angular 应用程序在启动时读取 cookie [英] How to make Angular application read cookies at start up
问题描述
我有一个 Angular
应用程序,它在启动时应该读取 Cookies
(app.component.ts
) 并且应该重定向到一个新组件传递读取值.我该怎么做?
I have an Angular
application which on start up should read Cookies
(app.component.ts
) and should redirect to a new component passing the read values. How can I do this?
目前,我的服务器将所需的值作为 html 标签属性提供给 <app-root>
(例如 <app-root something="someValue">
) 并且 AppComponent
使用 this.el.nativeElement.getAttribute("somethings")
读取属性.虽然它有效,但我更喜欢从 Cookies
或从 HTTP Header
Currently, my server provides the required values as html tag attributes to <app-root>
(eg <app-root something="someValue">
) and the AppComponent
reads the attributes using this.el.nativeElement.getAttribute("somethings")
. Though it works, I'll prefer to read the values from Cookies
or from say an HTTP Header
有没有办法做到这一点?
Is there a way to do this?
推荐答案
我很乐意接受其他答案,但目前的研究表明我正在尝试做的事情无法完成.引用来自 (在 JavaScript 中访问网页的 HTTP 标头), 不幸的是,没有 API 可以为您提供初始页面请求的 HTTP 响应标头.
.所以我目前正在做的可能是可能的解决方法之一1)我可以设置html属性.如果我担心安全性,我可以让它们 hidden
- https://www.w3schools.com/tags/att_global_hidden.asp2) 我可以在响应中设置 cookie 并使用普通的 javascript (document.cookies) 获取 cookie.https://www.w3schools.com/js/js_cookies.asp 和
I'll be happy to accept other answers but the research so far hints that what I am trying to do can't be done. Quoting a response from (Accessing the web page's HTTP Headers in JavaScript), Unfortunately, there isn't an API to give you the HTTP response headers for your initial page request.
. So what I am doing at the moment is probably one of the possible work arounds
1) I can set html attributes. If I am concerned about security, I can make them hidden
- https://www.w3schools.com/tags/att_global_hidden.asp
2) I can set cookies in the response and get the cookies using plain javascript (document.cookies). https://www.w3schools.com/js/js_cookies.asp and What is the equivalent to AngularJS's ngcookie in Angular 6?
这篇关于如何让 Angular 应用程序在启动时读取 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!