我正在尝试从"blog"获取数据并将其推送到"blogs",但发生错误



我得到以下错误:

**Error1:** Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables, such as Arrays. Did you mean to use the keyvalue pipe? 
**Error2:** this.blogs.push is not a function

我的代码是这样的:

export class BlogComponent {
blogs: Array<blogType>;
constructor() {
this.blogs = new Array<blogType>();
}
ngOnInit() {
this.blogs = JSON.parse(localStorage.getItem("blogs")!);
}
addBlog(title: any, content: any) {
let blog = new blogType(title.value, content.value);
if (localStorage.getItem('blogs')) {
this.blogs = JSON.parse(localStorage.getItem('blogs')!);
}
this.blogs.push(blog); //error occurs because of that line. Runtime error
localStorage.setItem('blogs', JSON.stringify(this.blogs));
title.value = '';
content.value = '';
alert('Blog Added!');
}

我正试图从"博客"中获取数据。数组并将其推入"blogs"数组,以便将其存储在本地存储器中。然而,由于以下行,我得到了一个错误:this.blogs.push(blog);

在解析并分配给this.blogs:

之前检查LocalStorage的内容是否为空
ngOnInit() {
var current = localStorage.getItem('blogs');
if (current !== null) {
this.blogs = JSON.parse(current);
}
console.log('this.blogs is: ' + this.blogs);
}

最新更新