@freelancercom/ngx-cookie

中文文档
6.0.0-fork.1发布于 2022/06/20MITTypeScriptES Module近 30 天下载 5810

Implementation of Angular 1.x $cookies service to Angular

原始使用文档
文档目录15 节
  1. Table of contents:
  2. Get Started
  3. Installation
  4. Usage
  5. Server Side Rendering
  6. Examples
  7. CookieService
  8. get()
  9. getObject()
  10. getAll()
  11. put()
  12. putObject()
  13. remove()
  14. removeAll()
  15. Options

ngx-cookie CI npm version Downloads

Implementation of Angular 1.x $cookies service to Angular

Table of contents:

Get Started

Installation

You can install this package locally with npm.

# To get the latest stable version and update package.json file:
yarn add ngx-cookie
# or
# npm install ngx-cookie --save

Usage

CookieModule should be registered in angular module with withOptions() static method. These methods accept CookieOptions objects as well. Leave it blank for the defaults.

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { CookieModule } from 'ngx-cookie';

import { AppComponent }  from './app.component';

@NgModule({
  imports: [ BrowserModule, CookieModule.withOptions() ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }
import { Component } from '@angular/core';
import { CookieService } from 'ngx-cookie';

@Component({
    selector: 'my-very-cool-app',
    template: '<h1>My Angular App with Cookies</h1>'
})

export class AppComponent { 
  constructor(private cookieService: CookieService){}
  
  getCookie(key: string){
    return this.cookieService.get(key);
  }
}

Server Side Rendering

ngx-cookie supports usage during Server Side Rendering (SSR / Angular Universal). Getting Server Side Rendering itself set up the first time can be tricky and is outside the scope of this guide. Here, we'll assume that you've got a working SSR setup similar to the Angular Universal Starter project, and you're just trying to get ngx-cookie working with SSR.

Note: during normal, client side usage, ngx-cookie manipulates the client cookies attached to the document object. During SSR, ngx-cookie will manipulate cookies in http request or response headers._

Setup

Install ngx-cookie-backend library:

yarn add ngx-cookie-backend
# or
# npm install ngx-cookie-backend --save

Then edit app.server.module.ts and add CookieBackendModule.withOptions() to imports:

/* app.server.module.ts */

import { CookieBackendModule } from 'ngx-cookie';

@NgModule({
  imports: [
    AppModule,
    ServerModule,
    CookieBackendModule.withOptions()
  ],
  bootstrap: [AppComponent]
})
export class AppServerModule {}

Next, we need to make providers for the 'REQUEST' and 'RESPONSE' objects created by the expressjs server during SSR. To do this, edit server.ts to create providers for 'REQUEST' AND 'RESPONSE'.

/* server.ts */
// All regular routes use the Universal engine
server.get('*', (req, res) => {
  res.render(indexHtml, {
    req,
    res,
    providers: [
      {provide: APP_BASE_HREF, useValue: req.baseUrl},
      {provide: REQUEST, useValue: req},
      {provide: RESPONSE, useValue: res}
    ]
  });
});

And that's it! all your application's calls to CookieService should now work properly during SSR!

Examples

Normal usage example is under projects/test-app

SSR usage example is under projects/backend-test-app

CookieService

There are 7 methods available in the CookieService (6 standard methods from Angular 1 and 1 extra removeAll() method for convenience)

get()

Returns the value of given cookie key.

/**
 * @param {string} key Id to use for lookup.
 * @returns {string} Raw cookie value.
 */
get(key: string): string;

getObject()

Returns the deserialized value of given cookie key.

/**
 * @param {string} key Id to use for lookup.
 * @returns {Object} Deserialized cookie value.
 */
getObject(key: string): Object;

getAll()

Returns a key value object with all the cookies.

/**
 * @returns {Object} All cookies
 */
getAll(): any;

put()

Sets a value for given cookie key.

/**
 * @param {string} key Id for the `value`.
 * @param {string} value Raw value to be stored.
 * @param {CookieOptions} options (Optional) Options object.
 */
put(key: string, value: string, options?: CookieOptions): void;

putObject()

Serializes and sets a value for given cookie key.

/**
 * @param {string} key Id for the `value`.
 * @param {Object} value Value to be stored.
 * @param {CookieOptions} options (Optional) Options object.
 */
putObject(key: string, value: Object, options?: CookieOptions): void;

remove()

Remove given cookie.

/**
 * @param {string} key Id of the key-value pair to delete.
 * @param {CookieOptions} options (Optional) Options object.
 */
remove(key: string, options?: CookieOptions): void;

removeAll()

Remove all cookies.

/**
 */
removeAll(): void;

Options

Options object should be a type of CookieOptions interface. The object may have following properties:

  • path - {string} - The cookie will be available only for this path and its sub-paths. By default, this is the URL that appears in your <base> tag.
  • domain - {string} - The cookie will be available only for this domain and its sub-domains. For security reasons the user agent will not accept the cookie if the current domain is not a sub-domain of this domain or equal to it.
  • expires - {string|Date} - String of the form "Wdy, DD Mon YYYY HH:MM:SS GMT" or a Date object indicating the exact date/time this cookie will expire.
  • secure - {boolean} - If true, then the cookie will only be available through a secured connection.
  • sameSite - {"Lax"|"Strict"|"None"} - Designates cookie for first party (Lax|Strict) or third party contexts.
  • httpOnly - {boolean} - If true, then the cookie will be set with the HttpOnly flag, and will only be accessible from the remote server. Helps to prevent against XSS attacks.
  • storeUnencoded - {boolean} - If true, then the cookie value will not be encoded and will be stored as provided.

版本与发布记录

@freelancercom/ngx-cookie 共发布 1 个版本,首次发布于 2022/06/20;过去 12 个月发布了 0 个版本。

版本发布日期距今
6.0.0-fork.1latest2022/06/204 年前

关于 @freelancercom/ngx-cookie 的常见问题

@freelancercom/ngx-cookie 是什么?

Implementation of Angular 1.x $cookies service to Angular

如何安装 @freelancercom/ngx-cookie?

在项目目录运行 npm install @freelancercom/ngx-cookie,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@angular/core(>=12.0.0)、@angular/common(>=12.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@freelancercom/ngx-cookie 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@freelancercom/ngx-cookie 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@freelancercom/ngx-cookie 可以商用吗?

@freelancercom/ngx-cookie 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@freelancercom/ngx-cookie 的下载量有多少?

根据 npm 官方下载统计,@freelancercom/ngx-cookie 在 2026/10/16 – 2026/11/14 这 30 天内被下载 5,810 次,日均约 194 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@freelancercom/ngx-cookie 还在维护吗?

最新版本 6.0.0-fork.1 发布于 2022/06/20(4 年前);至今共发布 1 个版本,其中过去 12 个月发布了 0 个;首次发布于 2022/06/20。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。