JS NG2 Firebase - 将foreach值添加到数组并在模板中使用

时间:2017-02-05 19:44:50

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

我想在我的模板中创建一个房间名称数组并将其提供给ngFor。值推入数组但看起来它们只在foreach中可用..我需要在模板中提供它们..这是我的组件

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import {AngularFire, FirebaseListObservable} from 'angularfire2';
import { Fb } from './firebase';
import 'rxjs/add/operator/map'; 

@Component({
  selector: 'page-message-overview',
  templateUrl: 'message-overview.html'
})

export interface ChatThreadOverview {
  roomname: string;
}

export class MessageOverviewPage {

  activeUser: string;
  threads:  FirebaseListObservable<any[]>;
  fb;
  af;
  public chatroom: ChatThreadOverview[] = [];

  constructor( public fire: Fb, af: AngularFire, public navCtrl: NavController, public navParams: NavParams) {
        this.fb         = fire.instance().database();
        this.af = af;
        this.activeUser = this.fire.instance().auth().currentUser.uid;

        this.threads = this.af.database.list('/message/u_'+ this.activeUser, { preserveSnapshot: true });
        this.threads.subscribe(snapshots => {
            snapshots.forEach(snapshot => {
              // console.log(snapshot.key)
              this.chatroom.push({ "roomname": snapshot.val().room });
              console.log( "Chat inside "+ JSON.stringify(this.chatroom ) )
            });
          })
          console.log( "Chat outside "+ JSON.stringify(this.chatroom ) );
  }

  ionViewDidLoad() { }

}

只是为了澄清有两个控制台输出基本上是foreach外面的一个触发,数组是空的,foreach中的一个每次都触发值。我需要这个值在foreach循环之外可用

1 个答案:

答案 0 :(得分:1)

这是一个异步调用,因此您注意到,这些值不会立即可用,并且console.log( "Chat outside "+ JSON.stringify(this.chatroom ) );会在订阅内的代码之前执行。一种解决方案是将关注chatroom的代码包装在div中,条件是只有chatroom中有值时才会显示模板的一部分。如下所示:

<div *ngIf="chatroom">
   <!-- your code here -->
</div>

除非聊天室中没有值,否则会从视图中删除div。我们假设这些值在某个时间可用:)

这样您的应用就不会抛出未定义的错误。你会习惯使用这个技巧,因为我们一直在处理Angular中的异步“问题”,最常见的是在检索数据之前渲染该视图,导致应用程序崩溃。

除了*ngIf之外的其他可能性是使用安全导航操作符,更多关于here这是另一个有用的东西。有了它,你可以使用例如:

<div *ngFor="let room of chatroom">
  <p>{{room?.yourProp}}</p>
</div>

其中yourProp是单个room的某些属性。