【问题标题】:Consuming json with Angular 5 and Laravel 5.5使用 Angular 5 和 Laravel 5.5 使用 json
【发布时间】: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());});

标签: php json angular


【解决方案1】:
getProducts() {
 this.http.get(this.url, {headers: 
 this.prepareHeaders()}).map(res=>res.json())
 .subscribe( p => {this.p = p; console.log(p);});
 }

这是一个很好的 Http.get 示例,带有 Observable 和 Promise Example

【讨论】:

    猜你喜欢
    • 2018-07-11
    • 2018-03-12
    • 2018-02-16
    • 2018-03-05
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多