【问题标题】:Accessing nested arrays from an API in Ionic从 Ionic 中的 API 访问嵌套数组
【发布时间】:2021-08-29 22:55:12
【问题描述】:

我目前正在制作一个应用程序,该应用程序旨在从 API 访问数据,以便在列表中显示信息。数据被构造为一个数组,其中每个条目也有自己的数组来显示条目,我目前试图弄清楚的是如何在列表中显示每个主要条目并访问辅助条目以修改点值使它们在一定的值范围内。

API 的界面如下所示

export interface RankingAPI {
    [x: string]: any;
    data: Data[];
}

export interface Data {
    points:   number;
    detail:   Detail[];
    userId:    number;
    firstName: string;
    lastName:  string;
    maxHr:     number;
}

export interface Detail {
    points:      number;
    workoutDate: Date;
}

主要的 Typescript 文件是什么样子的

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { RankingAPI } from "./rankingApi_interface";


@Component({
    selector: 'ranking',
    templateUrl: 'ranking.html'
})
export class RankList implements OnInit {
    public theTodo: RankingAPI;
    private _apiURL = '(api url being used)';
    constructor(
        private http: HttpClient
    ) {}
    ngOnInit(){
        this.http.get(this._apiURL).subscribe((data: RankingAPI) => {
            this.theTodo = data ;
            
            this.theTodo.data.forEach(item => {
                if (item.points == undefined) {
                    item.points = 0;
                }
            })
            
            console.log(this.theTodo.data);
        }) ;
    }
}

在 html 页面上显示条目也有问题,目前看起来像这样

<ion-header>
    <ion-navbar>
      <button ion-button menuToggle>
        <ion-icon name="menu"></ion-icon>
      </button>
      <ion-title>Ranking List</ion-title>
    </ion-navbar>
  </ion-header>

  <ion-content>
    <ion-list>
      <ion-item *ngFor="let item of data">
        {{item.userId}}
      </ion-item>
    </ion-list>
  </ion-content>

编辑:当该行更改为“let item of theTodo.data”时的样子

Console Screenshot

Screenshot of page

【问题讨论】:

    标签: javascript html ios angular ionic-framework


    【解决方案1】:

    您将数据存储在 theTodo.data 中,因此在您的 .html 中使用 theTodo.data 直接插入数据,如下所示:

    <ion-item *ngFor="let item of theTodo.data">
        {{item.userId}}
      </ion-item>
    

    【讨论】:

    • 谢谢,尽管我似乎收到了“无法读取未定义的属性‘数据’”。我会更新帖子以显示它的样子
    猜你喜欢
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 2022-12-12
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多