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

时间:2017-04-09 14:20:07

标签: json angular data-binding angular2-services

我是Angular 2的新手,我正在尝试创建发送get请求并获取json的服务。并将这些结果从json绑定到角度类的数组。但是当出现问题并出现问题时。 我按照angular.io上的文档进行了操作并完成了所有操作。通过调试器我发现当我写

return body.data

返回的对象未定义。

我收到了下一个错误:

 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"}]

实体类:

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

服务类:

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

1 个答案:

答案 0 :(得分:1)

您的回复对象没有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>