LoginSignup
1

More than 5 years have passed since last update.

AngularJSでCookieに有効期限(expires)を設定する

Posted at

AngularJSの標準の$cookiesでは有効期限(expires)を設定できないので、代わりにjquery.cookieを使って設定します。

index.html
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>

jquery.cookieのラッパークラスを作りました。これで、[モジュール名].Cookie.getで使用できるようになります。

Cookie.ts
/// <reference path="../../reference.ts" />
module [モジュール名] {
    /**
     * jquryを使ったCookieラッパークラス
     */
    export class Cookie {
        /**
         * 取得する
         * @param key キー
         * @returns string 値
         */
        public static get(key:string):string {
            return $.cookie(key);
        }

        /**
         * 設定する
         * @param key    キー
         * @param value  値
         * @param expire 有効期間(日数)
         */
        public static set(key:string, value:string, expire:number = 0):void {
            $.cookie(key, value, { expires: expire });
        }
    }
}

使用例としてはこんな感じです

app.ts
var locale = [モジュール名].Cookie.get("locale");
if(locale == undefined) {
    locale = "ja_JP";
    [モジュール名].Cookie.set("locale", locale, 36500);
}

※[モジュール名]は適宜変更してください

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
1