将Observable转换为数组angular 4 HTTP

时间:2017-10-06 21:36:36

标签: angular http typescript angular4-httpclient

我有一个在本地获取图书列表的服务我收到此错误:

BooksComponent.html:2 ERROR Error: Cannot find a differ supporting object 
'[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
    at NgForOf.webpackJsonp.../../../common/@angular/common.es5.js.NgForOf.ngOnChanges (common.es5.js:1681)
    at checkAndUpdateDirectiveInline (

这是我的服务类:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { Books } from './books';

@Injectable()
export class FetchbooksService {
books:any[];
  constructor(private _http:Http) { }
  fetch():Observable<Books[]>{
    return this._http.get('./assets/books.json').map(
      (response:Response)=> <Books[]>response.json(),
      error => console.log(error)
    ).do(data => console.log(data));
  }
}

这是组件:

import { Component, OnInit } from '@angular/core'; 
import { Observable } from 'rxjs/Observable';
import { FetchbooksService }  from  '../fetchbooks.service';
import { Books } from '../books';
@Component({
  selector: 'app-books',
  templateUrl: './books.component.html',
  styleUrls: ['./books.component.css']
})
export class BooksComponent implements OnInit {
 bookss:Books[];
   constructor(private _bookservice: FetchbooksService) {
    _bookservice.fetch().subscribe(
     (bookss)=> this.bookss = bookss,
      error => console.log(error)=
    );

   }

   ngOnInit() {
 }

}

书籍是一个界面 请告诉我,我做错了什么?

这是books.component.html:

 <ul>
  <li *ngFor = "let book of bookss ">
    Book: {{book.title}}
  </li>
</ul>

这是服务返回的数据:
console.log(bookss) result

1 个答案:

答案 0 :(得分:0)

如上所述,您没有收到数组,而是接收具有嵌套对象的对象。您需要使用自定义管道,或者然后转换组件中的数据。

如果您想使用自定义管道...这是要走的路,如果您需要维护密钥! ..我在这种情况下需要您成像。

导入必要的东西:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'keys' }) 
export class ValuesPipe implements PipeTransform {
    transform(value: any, args?: any[]): any[] {
        let keyArr: any[] = Object.keys(value),
            dataArr = [];
        keyArr.forEach((key: any) => {
            dataArr.push(value[key]);
        });
        return dataArr;
    }
}

ValuesPipe添加到模块中的declarations数组中,并在模板中使用它,如下所示:

<div *ngFor="let book of bookss | keys">
  {{book.author }} : {{ book.title }}
</div>

只是为了将来的提示,请记住,如果你选择管道,请记住它是否需要impure管道是非常昂贵的并经常被解雇。

如果数据的构建不需要保持与收到时相同。因此,在收到数据后,我会调用一种方法,使您的数据可以迭代,但是,这里你松开了密钥(需要一些修改才能保留密钥)

_bookservice.fetch().subscribe(
 (bookss) => {
    this.bookss = bookss.books;
    this.transform();
 },
  error => console.log(error)
);

transform(books) {
  let keyArr: any[] = Object.keys(books),
    dataArr = [];
    keyArr.forEach((key: any) => {
      dataArr.push(books[key]);
    });
  return dataArr;
}