在HTML上显示AngularFireList数据使我出错

时间:2018-08-02 02:13:15

标签: javascript angular firebase-realtime-database ionic3 angularfire2

我正在尝试在Home.html上显示从我的Firebase检索到的数据,但是我一遍又一遍地遇到相同的错误:

  

找不到类型为“对象”的其他支持对象“ [对象对象]”。 NgFor仅支持绑定到数组等Iterable。

你能帮我吗?

我的应用程序中包含以下代码:

user.service.ts

import { AngularFireList } from 'angularfire2/database/interfaces';
import { AngularFireDatabase } from 'angularfire2/database';

export class UserService {

  users: AngularFireList<User[]>;

  constructor(
    public http: HttpClient,
    public af: AngularFireDatabase
  ) {
    this.users = this.af.list('users');
  }

  create(user: User): void {
    this.af.list('users').push(user);
  }
}

home.ts

import { UserService } from './../../providers/user/user.service';
import { AngularFireList } from 'angularfire2/database/interfaces';

export class HomePage {

  users: AngularFireList<User[]>;

  constructor(
    public navCtrl: NavController,
    public userService: UserService
  ) {

  }

  ionViewDidLoad(){
    this.users = this.userService.users;
  }

home.html

<ion-content padding>

  <ion-list no-lines>
    <button ion-item *ngFor="let user of users">
      {{ user.name }}
    </button>
  </ion-list>

  <button ion-button block (click)="onSignUp()">Sign Up</button>
</ion-content>

2 个答案:

答案 0 :(得分:1)

更改此内容:

this.users = this.af.list('users');

对此:

this.users = this.af.list('users').valueChanges();

答案 1 :(得分:0)

编辑:2018-08-06

这解决了我的问题:

在我的user.service.ts上,我这样声明了var:

usersRef: AngularFireList<any>;
users: Observable<any[]>;

在构造函数中:

this.usersRef = this.af.list('users');
this.users = this.usersRef.valueChanges();
this.users.subscribe(res => console.log(res));

这样,我可以像这样从HTML上的“用户”中恢复值:

<ion-list no-lines>
    <button ion-item *ngFor="let user of users | async">
      {{ user.name }}
    </button>
</ion-list>

在home.ts中:

users: Observable<any[]>;

ionViewDidLoad(){
  this.users = this.userService.users;
}