Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 months ago.
How can you create cookies in Angular 6? For AngularJS there was ngcookie
. What is the equivalent way to create cookies in Angular 6?
You can use this node package for it
ngx-cookie-service
First of all, you should ask yourself: "Do I really need cookies ?" :
Cookies were once used for general client-side storage. While this was
legitimate when they were the only way to store data on the client, it
is recommended nowadays to prefer modern storage APIs. Cookies are
sent with every request, so they can worsen performance (especially
for mobile data connections). Modern APIs for client storage are the
Web storage API (localStorage and sessionStorage) and IndexedDB.
(Source: MDN)
So, if you haven't already, you may want to read about the Web Storage API instead.
If you do want to continue with cookies, please read on.
I tried ngx-cookie-service
and it didn't work for me. I had issue after issue, ended up discussing it on github, tried updating packages. It took me about a day to realize that what I needed did not have to be that complicated, after all getting/setting cookies is just a native javascript thing.
I had no more time to waste, and wrote this simple CookieService
myself. And I just wanted to share it with other desperate developers. :)
A simple CookieService
I created this gist , which is a lightweight alternative to ngx-cookie-service.
Setup and Usage
Of course you need to register it in your app.module.ts
file.
Add it to the list of your providers:
providers: [FooService, BarService, CookieService]
Next, use it in your components, e.g. as follows:
private _sessionId: string;
constructor(private cookieService: CookieService) {
this._sessionId = cookieService.get("sessionId");
}
public set sessionId(value: string) {
this._sessionId = value;
this.cookieService.set("sessionId", value);
}
Note that you can use the debug tools to verify that the cookie is actually set, and to verify that it is present in the subsequent HTTP requests. (screenshots of Chrome, but Firefox and Edge have similar overviews)
Now is: npm install ngx-cookie --save
Doc:
https://github.com/salemdar/ngx-cookie