What is the equivalent to AngularJS's ngcookie in Angular 6? [closed]

只谈情不闲聊 提交于 2019-12-03 18:48:55

问题


How can you create cookies in Angular 6? For AngularJS there was ngcookie. What is the equivalent way to create cookies in Angular 6?


回答1:


You can use this node package for it

ngx-cookie-service




回答2:


  1. npm install ngx-cookie-service --save
  2. Add to your module: import { CookieService } from 'ngx-cookie-service';
  3. Add CookieService to module's providers.
  4. Inject it into your constructor.
  5. Use cookie.get(nameOfCookie) for getting a specific cookie, use cookie.set(nameOfCookie,cookieValue) for adding a new cookie.



回答3:


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)




回答4:


Now is: npm install ngx-cookie --save

Doc: https://github.com/salemdar/ngx-cookie



来源:https://stackoverflow.com/questions/50772529/what-is-the-equivalent-to-angularjss-ngcookie-in-angular-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!