我尝试了所有从数据库中显示数据的方法。数据来自数据库,但是在用户界面上没有显示任何记录。当我打印console.log的数据时,它正确地显示出来。以下是我使用的代码片段,我是一个完全陌生的ionic开发,所以如果我犯了任何错误,请指出。
<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>
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窗口中,数据从数据库中正确地传来。
UserList[
0: {fullname: "shubham", email: "[email protected]", phone_no: "1230235420"}
1: {fullname: "johan", email: "[email protected]", phone_no: "120356452"}
2: {fullname: "aditya", email: "[email protected]", phone_no: "120356452"}
]
3个主要问题
1.你使用了let,而let是一个块的作用域,因此不会反映在类中。
解决方案:将 "let UserList = JSON.parse(JSON.stringify(data));
改为 "this.UserList = JSON.parse(JSON.stringify(data));"
2.绑定问题,因为你没有把索引放在数组值中,而不是传递一个对象值。
解决方法:更改:{{ UserList[Users].fullname.value }}。
到: {{用户全名}}
3.Minor你只对UserList对象进行了类型注释,因为它是用来迭代的。
解决方案 : 将 : UserList:any[];
改为: UserList:any[]=[]。
你做了一些错误的变量引用。我想只有 phone_no
应该显示。你引用的是数组,但它们是JSON对象的一部分。
正确的方式应该是。
{{Users.fullname}}
{{Users.email}}
{{Users.phone_no}}
最后,请注意 切勿 以大写字母开头的变量名称。让 user
而不是 User
. 仅大写字母的类。也许,我说的是也许,这段代码是在试图寻找 Users
类,这就是为什么它不能工作......。