ionic 5 - ng 不显示数据

ionic 5 - ngFor not showing data

我尝试了所有方法来显示数据库中的数据。数据来自数据库,但它不会在 UI 上显示任何记录。当我为数据打印 console.log 时,它是正确的。以下是我使用过的代码段,我是离子开发的新手,所以如果我犯了任何错误,请指出。

tab3.page.html

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      User List
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-button expand="block" (click)="getData()" >Get All users</ion-button>  
    <ion-list>
      <ion-item *ngFor="let Users of UserList">
            <h2>Hello {{ UserList[Users].fullname.value }}</h2>
            <p item-right> {{Users["email"]}}</p>
            <p>{{Users.phone_no}}</p>
      </ion-item>
    </ion-list>
</ion-content>

tab3.page.ts

import { Component } from '@angular/core';
import { ToastController, AlertController, LoadingController, NavController } from '@ionic/angular';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import {} from '../Login/tab1.module';
import { CommonModule } from "@angular/common";
import { setIndex } from '@ionic-native/core/decorators/common';

@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss']
})
export class Tab3Page {

    UserList:any[];
    LoginName:string = ""; 
    constructor(public navCtrl: NavController, public http: HttpClient) {

    }

    ionViewDidLoad(){
      console.log("Getting Users");
      this.getData(); 
    }

    getData()
    {
      this.http.get("http://localhost/MyFirstApp/GetAllUsers.php")
        .subscribe(
          data => {
                    let UserList = JSON.parse(JSON.stringify(data));
                    console.log(UserList);
                    console.log(UserList[1].fullname);
                    let i=0;
                    for (let Users in UserList){
                        this.LoginName = UserList[Users].fullname;
                    } 

                  }, 
          err => {
                    console.log(err);
                  }
      ); 
    }


}

数据正确地来自 console.log window

中的数据库
UserList[
0: {fullname: "shubham", email: "shubham@gmail.com", phone_no: "1230235420"}
1: {fullname: "johan", email: "johan@gmail.com", phone_no: "120356452"}
2: {fullname: "aditya", email: "aditya@gmail.com", phone_no: "120356452"}
]

您对变量的引用有误。我想应该只显示 phone_no。您引用的是数组,但它们是 JSON 对象的一部分。

正确的做法应该是:

{{Users.fullname}}
{{Users.email}}
{{Users.phone_no}}

最后,请不要 命名变量以大写字母开头。让 user 而不是 User。仅 classes 的大写字母。也许,我说也许,代码正在尝试寻找 Users class,这就是它不起作用的原因....

三个主要的东西:

  1. 您使用了 let,这是一个块范围,因此不会反映在 class.

    解法: 更改 let UserList = JSON.parse(JSON.stringify(data));
    this.UserList = JSON.parse(JSON.stringify(data));.

  2. 您遇到了绑定问题,因为您没有将索引放在数组值中,而是传递了一个对象值。

    解法: 更改 {{ UserList[Users].fullname.value }}
    {{Users.fullname}}.

  3. 您只对 UserList 对象进行了类型注释,因为它用于迭代。

    解法: 更改 UserList:any[];
    UserList:any[]=[];.