Ionic 将API json数据显示为离子折叠式

vsmadaxz  于 2022-12-08  发布在  Ionic
关注(0)|答案(1)|浏览(190)

我必须将API json数据(嵌套对象响应)显示为ion-accordion。如何实现?下面是component.ts和service文件的代码
组件.ts代码:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
@Component({
  selector: 'app-view',
  templateUrl: './view.component.html',
  styleUrls: ['./view.component.scss']
})
export class ViewComponent implements OnInit {

  users: any = [];
  constructor(private userdata: DataService) { }

  ngOnInit() {
    this.userdata.get().subscribe(data =>{
      this.users = [data];
      console.log(this.users);
    });
  }

}

服务代码:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(private http: HttpClient) { }

  get():Observable<any>{
    return this.http.get<any>(' ');
  }
}
xlpyo6sf

xlpyo6sf1#

这将取决于“this.users”的格式。但是您可以使用 *ngFor来创建您的accordion。
例如,如果在TS文件中有用户数据:

users = [{name: 'Michel', isPremium: true}, {name: 'Jean', isPremium: true}, {name: 'John', isPremium: false}];

在HTML文件中:

<ion-accordion-group>
 <ion-accordion *ngFor="let user of users">
   <ion-item slot="header">
     <ion-icon slot="start" name="star-outline" *ngIf="user.isPremium === true"></ion-icon>
    <ion-label>{{user.name}}</ion-label>
   </ion-item>
    <div slot="content">{{user.name}} is one of your user</div>
 </ion-accordion>
</ion-accordion-group>

相关问题