【项目心得】关于Angular中使用Cookie

发布时间 2023-09-22 15:04:06作者: SILL

今天写一个Angular前端项目时遇到需要使用Cookie的场景,bing寻找解决办法

  根据bing搜索第一条的方法,使用了一个名为”ngx-cookie-service“的库,结果方才一导入,就提示报错,报错信息如下:

  Error: Uncaught (in promise): Error: NG0203: inject() must be called from an injection context such as a constructor.

  于是乎继续寻找解决策略,三小时过去、无果。于是乎只能寻找其他途径。

  嘿您猜怎么着,还真让我找着了。末了一词之差,库名叫”ngx-cookie“。

 

ngx-cookie的使用

  在 app.module.ts 文件中导入 CookieModule

 1 import { CookieModule } from 'ngx-cookie'
 2 
 3 @NgModule({
 4   declarations: [
 5     AppComponent,
 6     LoginComponent
 7   ],
 8   imports: [
 9     // 下面这一行
10     CookieModule.withOptions(),
11 
12     // ...
13   ],
14   providers: [],
15   bootstrap: [AppComponent]
16 })
17 export class AppModule { }

  在组件 xxx.component.ts 文件处注入 CookieService

 1 import { CookieService } from 'ngx-cookie'
 2 
 3 @Component({
 4   selector: 'app-login',
 5   templateUrl: './login.component.html',
 6   styleUrls: ['./login.component.sass'],
 7   // providers: [CookieService]
 8 })
 9 export class LoginComponent {
10   // 注入
11   cookieService = inject(CookieService)

  注入后便可以在组件中执行Cookie的写入和读取

1 var date = new Date()
2 date.setSeconds(date.getSeconds() + 60 * 60 * 24 * 3)
3 console.log(date.toDateString()) 
4 this.cookieService.put("user", JSON.stringify(result.data[0]), {
5     path: '/',
6     expires: date,
7 })