I'm getting the following error:
**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
My code looks like this:
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!');
}
I am trying to take data from the "blog" array and push it to the "blogs" array in order to store it in the localstorage. Yet I get an error because of the folowing line: this.blogs.push(blog);
CodePudding user response:
Check the contents of LocalStorage for null before you parse it and assign to this.blogs:
ngOnInit() {
var current = localStorage.getItem('blogs');
if (current !== null) {
this.blogs = JSON.parse(current);
}
console.log('this.blogs is: ' this.blogs);
}