如何使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标头),Unfortunately, there isn't an API to give you the HTTP response headers for your initial page request.
.因此,我目前正在做的事情可能是可能的解决方法之一
1)我可以设置HTML属性.如果我担心安全性,可以将其设置为hidden
- https://www.w3schools .com/tags/att_global_hidden.asp
2)我可以在响应中设置cookie并使用纯JavaScript(document.cookies)获取cookie. https://www.w3schools.com/js/js_cookies.asp 和与Angular 6中AngularJS的ngcookie等效吗?
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屋!