Angular 2中Cookie值页面刷新丢失,如何持久化并控制有效期?
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:
- 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. - No expiry date set: By default, cookies created with
CookieServiceare session cookies—they disappear as soon as the browser closes. You need to explicitly set an expiry to make them stick. - 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); } }
How to Control Cookie Expiry
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.,
30for 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

