问题描述:在Angular中使用本地存储存储数组,并尝试在HTML上显示数组内容,但数组没有显示。
解决方法:
// 导入必要的模块
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
// 定义一个数组
myArray: Array = [];
constructor() { }
ngOnInit(): void {
// 从本地存储中获取保存的数组
const storedArray = localStorage.getItem('myArray');
if (storedArray) {
this.myArray = JSON.parse(storedArray);
}
}
// 将数组保存到本地存储中
saveArray(): void {
localStorage.setItem('myArray', JSON.stringify(this.myArray));
}
}
{{ item }}
// 导入必要的模块
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
// 定义一个数组
myArray: Array = [];
constructor(private router: Router) { }
ngOnInit(): void {
// 从本地存储中获取保存的数组
const storedArray = localStorage.getItem('myArray');
if (storedArray) {
this.myArray = JSON.parse(storedArray);
}
}
// 将数组保存到本地存储中
saveArray(): void {
localStorage.setItem('myArray', JSON.stringify(this.myArray));
// 重新加载页面或重新渲染组件
this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
this.router.navigate(['/example']);
});
}
}
这样,当调用保存数组的方法时,页面将被重新加载或重新渲染,以显示最新的数组内容。
下一篇:Angular本地化混淆