使用 angular 4 保存 cookie

use*_*429 8 cookies angular-cookies angular

我有一个基于 ldap 的身份验证,如果用户凭据匹配,则接收承载令牌和 userId 作为 JSON 格式的响应。现在我需要将这些值保存在 cookie 中。我正在使用 angular 4。我找不到任何与 angular 4 相关的 cookie 示例。

Cod*_*ior 7

我知道回答这个问题有点晚了,但你可以使用ngx-cookie-service节点包。

1.安装

npm install ngx-cookie-service --save
Run Code Online (Sandbox Code Playgroud)

2. 然后将 cookie 服务作为提供者添加到您的 app.module.ts 中:

@NgModule({
  ...,
  providers: [ CookieService ]
})
Run Code Online (Sandbox Code Playgroud)

3. 然后,将其导入并注入到组件中:

import { CookieService } from 'ngx-cookie-service';

constructor( private cookieService: CookieService ) { }

  ngOnInit(): void {
    this.cookieService.set( 'Test', 'Hello World' );
    this.cookieValue = this.cookieService.get('Test');
  }
Run Code Online (Sandbox Code Playgroud)

4. 一切就绪