我有一个如下的响应对象:
javascript - 无法在angular2中循环json对象-LMLPHP
如果我遍历此对象,则会给我错误
错误TypeError:无法读取未定义的属性'forEach'
我的代码:

 getBooklist() {
         return this.http.get('https://anytime-library-d705a.firebaseio.com/books.json')
      .pipe(map((res: Response) => res.json()));
    }

this.dataStoreService.getBooklist()
    .subscribe((booklist: Book[]) => {
        console.log(booklist);
        this.books = [];
        booklist.forEach(element => {
          const y = element;
          this.books.push(y as Book);
        });

最佳答案

booklist是对象,而不是数组。

您必须使用Object.keys方法。

Object.keys(booklist).forEach(key=> {
    this.books.push(booklist[key] as Book);
});

09-18 16:02