array-uri - Încerc să iau date din „blog” și să le împing în „blogs”, dar apare o eroare


Primesc următoarea eroare:

**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

Codul meu arată astfel:

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!');
  }

Încerc să iau datele din array-ul „blog” și să le împing în array-ul „blogs” pentru a le stoca în localstorage. Totuși, primesc o eroare din cauza următoarei linii: this.blogs.push(blog);

Răspuns #1

Verifică conținutul LocalStorage pentru null înainte de a-l analiza și a-l atribui la this.blogs:

ngOnInit() {
    var current = localStorage.getItem('blogs');
    if (current !== null) {
      this.blogs = JSON.parse(current);
    }
    console.log('this.blogs is: ' + this.blogs);
  }