LoginSignup
11
15

More than 5 years have passed since last update.

Angular 5でcookieを利用する

Last updated at Posted at 2018-04-30

動作確認した環境

PS > ng --version

    _                      _                 ____ _     ___
   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
               |___/

Angular CLI: 1.7.4
Node: 8.11.1
OS: win32 x64
Angular: 5.2.10
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

@angular/cli: 1.7.4
@angular-devkit/build-optimizer: 0.3.2
@angular-devkit/core: 0.3.2
@angular-devkit/schematics: 0.3.2
@ngtools/json-schema: 1.2.0
@ngtools/webpack: 1.10.2
@schematics/angular: 0.3.2
@schematics/package-update: 0.3.2
typescript: 2.5.3
webpack: 3.11.0

上記とあわせ、Google Chrome バージョン: 65.0.3325.181(Official Build) (64 ビット)で動作を確認。

利用モジュール:ngx-cookie-service

  • インストール
npm install ngx-cookie-service --save

利用方法

設定

  • app.module.tsのproviderに設定を追加
import { CookieService } from 'ngx-cookie-service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [CookieService ],
  bootstrap: [AppComponent]
})
  • 利用するコンポーネントでもインポート
import { CookieService } from 'ngx-cookie-service';

constructor(
    private cookieService: CookieService
 ) { }

操作

cookieに保存

this.cookieService.set( 'test-key', 'test value' );

cookieからの読み取り

cookieValue = this.cookieService.get('test-key');

全ての項目を読み取り

const allCookies: {} = cookieService.getAll();

全ての項目を削除

cookieService.deleteAll();

Expires/Max-Age設定

  • デフォルト(指定無しの場合)は、「1969-12-31T23:59:59.000Z」が設定される。
    • 恐らく無期限では無さそう?
  • 日数指定の場合は、numberを指定(例:3日間の場合)
this.cookieService.set( 'test-expire', 'test-value', 3 );
  • 日時指定の場合は、Dateを指定(例:2018-05-04T23:59:59.000Zの場合)
const date: Date = new Date('2018-05-04T23:59:59.000Z');
this.cookieService.set( 'test-expire2', 'test-value2', date );
11
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
15