【发布时间】:2017-12-15 21:41:38
【问题描述】:
我有这个 Api 我不知道如何使用或访问数据数组 我试试这个,但我没有得到 P 中的产品列表 我得到了这个 API
{"data":[{"name":"product1","price":55,"created_at":"2017-11-29 00:00:00","updated_at":"2017-11-29 00:00:00"},{"name":"product2","price":250,"created_at":"2017-12-09 00:00:00","updated_at":"2017-12-09 00:00:00"}]}
我的 Angular 代码
p:Product[];
constructor(private http: Http) {
this.url = 'http://127.0.0.1:8000/api/products';
}
getProducts() {
this.http.get(this.url, {headers: this.prepareHeaders()}).map(res=>res.json())
.subscribe( p => this.p = p);
console.log(this.p.toString());
}
【问题讨论】:
-
http 请求是异步的。您不能在异步调用完成之前执行
this.p.toString()。您要在this.p上执行的任何操作都必须在您收到数据后发生。所以你可以做类似.subscribe(p => {this.p = p; console.log(this.p.toString());});