2017-03-21 60 views
0

我对Firebase以及angular2相当陌生。所以我正在尝试通过教程制作Firebase集成的angular2聊天应用程序。我已按照 this tutorial制作聊天应用程序。问题是,除了简单聊天之外,我想在有人写信或接收新聊天时创建敬酒。但我似乎无法找到可以听到该事件的代码。收听聊天事件

任何想法在哪里可以找到它?

角度分量看起来像这样

import { Component } from '@angular/core'; 
import { AngularFire, AuthProviders, AuthMethods, FirebaseListObservable } from 'angularfire2'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 

export class AppComponent { 
    items: FirebaseListObservable<any>; 
    name: any; 
    msgVal: string = ''; 

    constructor(public af: AngularFire) { 

     this.items = af.database.list('/messages', { 
      query: { 
      limitToLast: 5 
      } 
     }); 

     this.af.auth.subscribe(auth => { 
      if(auth) { 
      this.name = auth; 
      } 
     }); 
    } 

login() { 
    this.af.auth.login({ 
     provider: AuthProviders.Facebook, 
     method: AuthMethods.Popup, 
    }); 
    } 

chatSend(theirMessage: string) { 
     this.items.push({ message: theirMessage, name: this.name.facebook.displayName}); 
     this.msgVal = ''; 
    } 
} 

,这是HTML标记

<div class="row columns"> 
    <button (click)="login()" *ngIf="!name">Login With Facebook</button> 

    <input type="text" id="message" *ngIf="name" placeholder="Chat here..." (keyup.enter)="chatSend($event.target.value)" [(ngModel)]="msgVal" /> 

    <div class="chat-container" *ngFor="let item of items | async"> 
     <a href="#">{{item.name}}</a> 

     <p>{{item.message}}</p> 
    </div> 
</div> 

回答

0

其中Gentlement从reddit的帮助我,并告诉检查FirebaseObservables,并听取了关于它的变化。

initializeApp(firebaseConfig); 
database().ref().on('value', function(snapshot){ 

    var x = snapshot.val() 
    console.log("This prints whenever there is a new message"); 
}); 

只要聊天线程中有新消息,主模块内的此片段就会触发。

希望它可以帮助别人