尝试将blog数据存入blogs数组并存储到localStorage时遇报错求助
问题解决:
this.blogs.push is not a function 及 NgFor 绑定错误 错误原因分析
this.blogs.push is not a function:当localStorage.getItem("blogs")返回null时,JSON.parse(null)会得到null,此时this.blogs被赋值为null而非数组;如果之前误将单个对象存入localStorage,this.blogs会变成对象,这两种情况都无法调用数组的push方法。- NgFor 绑定错误:
*ngFor仅支持遍历可迭代对象(如数组),当this.blogs是null或普通对象时,就会抛出该错误。
解决方法
核心思路是确保blogs始终为数组类型,在任何赋值场景下都做类型校验和兜底处理:
修改后的代码
export class BlogComponent { // 直接初始化空数组,避免初始值异常 blogs: Array<blogType> = []; ngOnInit() { const storedBlogs = localStorage.getItem("blogs"); // 解析后判断,非数组则重置为空数组 this.blogs = storedBlogs ? JSON.parse(storedBlogs) : []; if (!Array.isArray(this.blogs)) { this.blogs = []; } } addBlog(title: any, content: any) { const blog = new blogType(title.value, content.value); const storedBlogs = localStorage.getItem('blogs'); if (storedBlogs) { this.blogs = JSON.parse(storedBlogs); // 强制校验数组类型,避免旧数据异常 if (!Array.isArray(this.blogs)) { this.blogs = []; } } else { this.blogs = []; } this.blogs.push(blog); localStorage.setItem('blogs', JSON.stringify(this.blogs)); title.value = ''; content.value = ''; alert('Blog Added!'); } }
额外处理
如果之前localStorage中存了非数组数据,可在浏览器控制台执行localStorage.removeItem('blogs')清理旧数据,确保后续存储的是标准数组格式。
内容的提问来源于stack exchange,提问作者Nurbala Kaldybekova
相关产品推荐
相关产品推荐

