How to make Angular application read cookies at st

2020-05-06 03:52发布

问题:

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?

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?

回答1:

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?