我尝试了所有的方法来显示数据从数据库(Firebase实时数据库)有以下配置规则:
{
"rules": {
".read": "true",
".write": "true"
}
}
数据来自数据库(Firebase实时数据库),但是它没有在UI上显示任何记录。当我打印数据的console.log
时,它是正确的。以下是我所使用的代码段,我是Ionic开发的新手,所以如果我犯了任何错误,请指出。
home.page.html
<ion-header [translucent]="true">
<ion-toolbar>
<ion-title>
Blank
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content [fullscreen]="true">
<ion-header collapse="condense">
<ion-toolbar>
<ion-title size="large">Blank</ion-title>
</ion-toolbar>
</ion-header>
<ion-list>
<ion-item *ngFor="let user of users">
<ion-thumbnail slot="start">
<img [src]="user.avatar">
</ion-thumbnail>
<ion-label>
{{ user.first_name}}
</ion-label>
</ion-item>
</ion-list>
</ion-content>
home.page.ts
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
users:any[]=[];
constructor(private http: HttpClient) {}
ngOnInit(){
this.http.get("https://food-ea070-default-rtdb.firebaseio.com/users.json").subscribe(data=>{
this.users = JSON.parse(JSON.stringify(data));
console.log("Data", data);
});
}
}
数据正确地从console.log
的数据库来。
{"0":
{"avatar":"https://firebasestorage.googleapis.com/v0/b/food-ea070.appspot.com/o/polloalabrasa.jpg?alt=media&token=5b226d30-2eb2-417d-9c94-c1b25e9890fa","email":"michael.lawson@reqres.in","first_name":"Michael","id":7,"last_name":"Lawson"},
"-MUsoe5L3d3F1-E-nmC_":
{"avatar":"https://reqres.in/img/faces/1-image.jpg","email":"george.bluth@reqres.in","first_name":"George","id":1,"last_name":"Bluth"},
"-MUsoqU00M9v0QR772aK":
{"avatar":"https://reqres.in/img/faces/2-image.jpg","email":"janet.weaver@reqres.in","first_name":"Janet","id":2,"last_name":"Weaver"},
"-MUsotIie6a5cU62E_UK":
{"avatar":"https://reqres.in/img/faces/3-image.jpg","email":"emma.wong@reqres.in","first_name":"Emma","id":3,"last_name":"Wong"},
"-MUsp1tWC4ABqPvDLgs9":
{"avatar":"https://reqres.in/img/faces/5-image.jpg","email":"charles.morris@reqres.in","first_name":"Charles","id":5,"last_name":"Morris"},
"-MUsp4Qm0Cyd9sfgcZ7m":
{"avatar":"https://reqres.in/img/faces/6-image.jpg","email":"tracey.ramos@reqres.in","first_name":"Tracey","id":6,"last_name":"Ramos"}
}
Your "data"是JSON对象,但不是数组。
{
"0": {
"avatar": "https://firebasestorage.googleapis.com/v0/b/food-ea070.appspot.com/o/polloalabrasa.jpg?alt=media&token=5b226d30-2eb2-417d-9c94-c1b25e9890fa",
"email": "michael.lawson@reqres.in",
"first_name": "Michael",
"id": 7,
"last_name": "Lawson"
},
...
}
在你的模板中,users被当作一个数组。
<ion-item *ngFor="let user of users">
首先要将数据对象转换为数组
let users = Object.values(data);