【问题标题】:Problem trying to get values from my API Ionic 4尝试从我的 API Ionic 4 获取值时出现问题
【发布时间】:2020-05-04 17:07:39
【问题描述】:

我正在尝试从我的 API 中获取值,但我无法在 ion-list 中显示它们。

错误截图:

正如您在图片中看到的,我从我的 API 中获取了数据,但我可以在 ion-list 中显示它们。

HTML 是这样的

<ion-list>
<ion-item *ngFor="let item of (results | async)">

  <ion-label text-wrap>{{item.nombreProducto}}</ion-label>
  <ion-button color="light"><img src="../../assets/icon/binoculars.png" alt="" (click)="presentarModal()" item-end></ion-button>
  <ion-button color="light"><img src="../../assets/icon/cart.png" alt="" (click)="addCart()" item-end></ion-button>
</ion-item>

我创建了一个服务,它有一个名为 getAll 的方法

   getAll(): Observable<any>{
    return this.http.get(`${this.url}`).pipe(
      map(results=>{
        console.log('Data', results);
        return results['Data'];
      })
    );
  }

在我的 home.page.ts 中,getAll 方法包含这个

getAll(){
  this.results = this.productService.getAll();
}

【问题讨论】:

  • 响应数据是数组吗?

标签: ionic-framework ionic4


【解决方案1】:

您正在尝试访问数组中不存在的键。您的results 是您要查找的要返回的数据。将您的方法更新为以下内容:

getAll(): Observable<any>{
return this.http.get(`${this.url}`).pipe(
  map(results=>{
    console.log('Data', results);
    return results;
  })
);

【讨论】:

  • 还有一个问题,应该如何搜索?因为我使用像 getAll 这样的但不工作
  • @RoberthTorres 如果results 是一个数组,您可以在数组上使用.filter 方法来搜索特定项目,然后您可以遍历过滤器方法的结果并识别您正在寻找的项目。
  • 是一个对象,我在想这样的事情但不起作用searchData(codigo: number): Observable&lt;any&gt; { return this.http.get(${this.url}/${codigo}).pipe( map(results =&gt; { console.log('Data', results); return results; }) ); }
【解决方案2】:

对于 Angular 4.x 及更高版本,异步管道的语法以及如何在 ngFor 中引用它的值可能不正确,请尝试:

<ion-list>
<ion-item  *ngFor="let item of results | async as item">

  <ion-label text-wrap>{{item.nombreProducto}}</ion-label>
  <ion-button color="light"><img src="../../assets/icon/binoculars.png" alt="" (click)="presentarModal()" item-end></ion-button>
  <ion-button color="light"><img src="../../assets/icon/cart.png" alt="" (click)="addCart()" item-end></ion-button>
</ion-item>

Angular 版本之间的这种语法变化在这里得到了更好的解释:

“虽然在版本 2 中我们不得不回退到订阅组件类中的 Observable,但 Angular 版本 4 现在让我们可以通过将来自 Observable 的异步结果分配给模板变量来处理这种情况”

https://juristr.com/blog/2017/06/new-enhanced-ngIf-and-ngFor/#enumerate-ngfor-loops-using-as-and-async-pipes

【讨论】:

    【解决方案3】:

    results 是一个对象数组,您在不存在的 rxjs map 中返回 results['Data']。我假设您自己的 console.log 让您误以为该结构具有 Data 属性。

    【讨论】:

      猜你喜欢
      • 2020-04-15
      • 1970-01-01
      • 2020-01-16
      • 2021-11-26
      • 2020-07-02
      • 1970-01-01
      • 2020-06-27
      • 2017-05-10
      • 1970-01-01
      相关资源
      最近更新 更多