You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 2中Cookie值页面刷新丢失,如何持久化并控制有效期?

Fixing Persistent Cookies with Expiry in Angular

Hey there! Let's work through your cookie persistence issue—looks like a couple of small syntax and logic gaps are causing your data to vanish on refresh. Here's how to fix it step by step:

First, Let's Address the Core Issues in Your Code

Your current approach has three key problems that are breaking persistence:

  1. Cookies only store strings: You’re trying to save a raw array directly, which gets converted to a useless [object Object] string instead of your actual shop data.
  2. No expiry date set: By default, cookies created with CookieService are session cookies—they disappear as soon as the browser closes. You need to explicitly set an expiry to make them stick.
  3. Template string syntax errors: You’re using ${} without wrapping the entire value in backticks, which throws syntax errors and breaks your code.

Corrected Code Walkthrough

Assuming you’re using ngx-cookie-service (the most popular Angular cookie library), here’s the fixed version of your AppComponent:

import { Component, OnInit } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';

export class AppComponent implements OnInit { 
  dislikedShops: string[] = [];

  constructor(private cookieService: CookieService){ } 

  ngOnInit() {
    // Initialize the array from saved cookie on component load
    const savedShops = this.cookieService.get('dislikedShops');
    if (savedShops) {
      // Parse the saved string back to an array
      this.dislikedShops = JSON.parse(savedShops);
    }
  }

  onShopDisliked(shopTitle: string) { 
    // Add the new shop to the array
    this.dislikedShops.push(shopTitle);
    
    // Set expiry to 7 days from now (adjust this as needed)
    const expiryDate = new Date();
    expiryDate.setDate(expiryDate.getDate() + 7);
    
    // Serialize the array to a string and save with expiry
    this.cookieService.set(
      'dislikedShops', 
      JSON.stringify(this.dislikedShops), 
      expiryDate // This line ensures the cookie persists across browser sessions
    );

    console.log('Updated disliked shops:', this.dislikedShops);
  } 
}

The set method of CookieService gives you flexible control over expiry via the third parameter:

  • Date object: Like the example above, set a specific future date (e.g., 7 days from now)
  • Number of days: Pass a number directly to set expiry in days (e.g., 30 for 30 days)
  • Date string: Use a valid date string (e.g., '2024-12-31') for a fixed expiry date

Example of setting expiry for 30 days with a number:

this.cookieService.set('dislikedShops', JSON.stringify(this.dislikedShops), 30);

Bonus: LocalStorage Alternative (If You Don’t Need Cross-Domain Support)

You mentioned trying localStorage—since it persists by default (until the user clears their browser data), it’s a simpler option if cross-domain cookie sharing isn’t required. Here’s how that would look:

ngOnInit() {
  const savedShops = localStorage.getItem('dislikedShops');
  if (savedShops) {
    this.dislikedShops = JSON.parse(savedShops);
  }
}

onShopDisliked(shopTitle: string) {
  this.dislikedShops.push(shopTitle);
  localStorage.setItem('dislikedShops', JSON.stringify(this.dislikedShops));
}

Key Takeaways

  • Always serialize arrays/objects to strings with JSON.stringify() when saving to cookies or localStorage.
  • Parse saved data back to its original type with JSON.parse() when retrieving it.
  • Set an explicit expiry date for cookies if you want them to survive browser restarts.

内容的提问来源于stack exchange,提问作者Hicham Moro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:46:03