web-dev-qa-db-ja.com

ngx-cookieサービスなしでangular 6のcookieにアクセスする方法

  login() : any {
    for(let data of this.loginsdata)
    if(this.username == data.usr && this.password == data.pw){
      // this.toastr.success('logged in');
      console.log(this.username);
      console.log(this.password);
      
      this.router.navigate(['table']);
      
    }
    document.cookie =?
  <script type="text/javascript" src="TypeScript.compile.min.js"></script>

angular 6で、ng-xcookieサービスのような外部モジュールなしでcookieにアクセスしたい。getsetdeleteを使用したい。方法はありますか?documentのようなjavascriptアプローチで実行しました。クッキーですが、そのスローエラー

2
Akhil Raghav

ブラウザのドキュメントオブジェクトを使用して実装されます。

// Set Cookiee
// "Secure;HttpOnly;" will work if your site is having SSL certificate.
// You can ignore these 2 attributes in development.
document.cookie = `myKey=${myValue};Path=/;Secure;HttpOnly;`;

// Read Cookiee
const _name = 'myKey',
let value = `; ${document.cookie}`.match(`;\\s*${_name}=([^;]+)`);

// Delete Cookiee (using expiration time)
const expires = 'expires=' + new Date().toUTCString();
document.cookie = `myKey=;Path=/;expires=${expires}`;

ただし、サーバーサイドレンダリング(Angular Universal)の実装では、デフォルトのブラウザードキュメントオブジェクトを使用しないでください。その場合、ngx-cookieeが役立ちます。