【问题标题】:How to fetch data from api by angular 5如何通过角度5从api获取数据
【发布时间】: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 返回 Obsdervablearray 而不是 object
  • 尝试像this.products = res.json()一样解析成JsON
  • 你能详细解释一下吗
  • 您的res 是什么样的?你能做一个console.log(res) 并向我们展示输出吗?

标签: php angular


【解决方案1】:

试试这个可能会有所帮助,也可以查看 console.log 的值

 showProducts() {
          this.data.showProducts().subscribe(res => {
                 this.products = res;
                console.log(this.products);
           });
  }

【讨论】:

    【解决方案2】:

    我怀疑来自后端的响应。

    showProducts() {
    this.data.showProducts()
      .subscribe(res => this.products = res);
    }
    

    只需检查此处的“res”。它可能不是一个数组,因此是产品。

    【讨论】:

      【解决方案3】:

      您的 API 响应必须是 JSON 格式,否则您应该在您的服务中明确声明 respondType。类似:

         apiUrl = 'http://localhost:8000/api/v1/products'
         showProducts() {
              return this.http.get<Product[]>(this.apiUrl, {observe: 'response', 
         resposeType: 'text'});
         }
      

      您的 DOM 或组件似乎没有问题。

      【讨论】:

        【解决方案4】:

        试试这个方法,它会有所帮助,还可以优化和检查控制台日志值

        showProducts(): void {
          this.data.showProducts().subscribe(( this.products: any) => {
            console.log(this.products); 
            });
          }
        

        【讨论】:

          猜你喜欢
          • 2018-11-06
          • 2019-03-21
          • 1970-01-01
          • 2018-11-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-10-24
          • 1970-01-01
          相关资源
          最近更新 更多