【发布时间】:2018-05-09 11:35:45
【问题描述】:
我有从我的 api 获取数据的数据服务:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { HttpClient, HttpParams } from '@angular/common/http';
@Injectable()
export class DataService {
constructor(private http: HttpClient) { }
showProducts(){
return this.http.get('http://localhost:8000/api/v1/products');
}
}
和我的组件
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
//import { Products } from '../products';
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {
products;
constructor(private data:DataService) { }
ngOnInit() {
this.showProducts();
}
showProducts() {
this.data.showProducts()
.subscribe(res => this.products = res);
}
}
和我的 html 组件:
<div>
<table border="1">
<tr>
<th>Product</th>
<th>Code</th>
<th>Price</th>
<th>Action</th>
</tr>
<tr *ngFor="let product of products">
{{product.product_name}}
</tr>
</table>
</div>
我在浏览器中运行代码时遇到此错误的问题:
1- 错误错误:找不到类型为“object”的不同支持对象“[object Object]”。 NgFor 只支持绑定到 Arrays 等 Iterables。
2- 错误上下文 DebugContext_ {view: {…}, nodeIndex: 21, nodeDef: {…}, elDef: {…}, elView: {…}}
【问题讨论】:
-
确保 API 返回
Obsdervable的array而不是object -
尝试像
this.products = res.json()一样解析成JsON -
你能详细解释一下吗
-
您的
res是什么样的?你能做一个console.log(res)并向我们展示输出吗?