无法将对象从 json 绑定到 angular 2 class

Can't bind objects from json to angular 2 class

我是 Angular 2 的新手,我正在尝试创建发送获取请求并获取 json 的服务。并将 json 的结果绑定到 angular classes 的数组。但是当遇到麻烦,出问题的时候。 我遵循了 angular.io 上的文档,并按照那里的方式做了所有事情。通过调试器我发现当我写

return body.data

在 returns 未定义的对象之后。

我遇到下一个错误:

 Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

请帮我解决这个问题。

Json数据:

[{"categoryId":1,"categoryName":"cpu"},{"categoryId":2,"categoryName":"gpu"},{"categoryId":3,"categoryName":"motherboard"},{"categoryId":4,"categoryName":"phone"},{"categoryId":5,"categoryName":"hdd"},{"categoryId":6,"categoryName":"ssd"},{"categoryId":7,"categoryName":"ram"},{"categoryId":8,"categoryName":"rom"}]

实体class:

export class Category {
  constructor(public categoryId: number, public categoryName: string) {}
}

服务class:

@Injectable()
export class CategoryService {
  private currentUrl = 'http://localhost:8081/emusicshop/api/categories';

  constructor (private http: Http) {}

  getCategories(): Observable<Category[]> {
    return this.http.get(this.currentUrl)
      .map(this.extractData)
      .catch(this.handleError);
  }

  private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
  }
  private handleError (error: Response | any) {
    // In a real world app, you might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
}

组件:

Component
export class CategoryComponent implements OnInit {

  allCategories: Category[];

  constructor(private service: CategoryService) { }

  getCategories(): void {
    this.service.getCategories().subscribe(
      categories => this.allCategories = categories);
  }

  ngOnInit() {
    this.getCategories();
  }

}

HTML 文件:

<ul>
  <li *ngFor="let categ of allCategories">
    Id : {{categ.id}}
    Name : {{categ.name}}
  </li>
</ul>

您的响应对象没有 data 字段。应该更像这样:

private extractData(res: Response) {
    let body = res.json();
    return body || []; //<-- return an empty array instead of an object so *ngFor won't complain about iteration
}

并尝试在您的模板上使用安全导航运算符?

<ul>
  <li *ngFor="let categ of allCategories">
    Id : {{categ?.categoryId}}
    Name : {{categ?.categoryName}}
  </li>
</ul>