错误 - 订阅AngularFireObject时没有显示用户名 - Ionic3聊天移动应用程序

时间:2017-12-08 02:28:56

标签: firebase ionic-framework ionic2 ionic3

我正在尝试使用Ionic 3和Firebase创建一个简单的聊天应用程序。注册,登录用户,发送和显示他们的消息都有效。这是所有用户的常见聊天室。

当用户登录或退出以让其他用户知道时,我希望在聊天室中显示一条消息。当测试用户登录时,会显示以下消息: "已加入房间"

当测试用户注销时,会显示以下消息: " test@gmail.com离开了房间"

我喜欢在用户登录时显示的用户名(电子邮件地址)。我希望此消息显示:" test@gmail.com已加入会议室"

我尝试在控制台上编写this.username,但它没有向控制台写任何东西。

chat.ts:



import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { AngularFireDatabase, AngularFireObject } from 'angularfire2/database';
import { Storage } from '@ionic/storage';
import { Subscription } from 'rxjs/Subscription';
import $ from 'jquery';

@IonicPage()
@Component({
  selector: 'page-chat',
  templateUrl: 'chat.html',
})
export class ChatPage {

  username: string= '';
  message: string= '';
  obsRef: AngularFireObject<any>;
  obsToData: Subscription;
  messages: object[]= [];

  constructor(public db: AngularFireDatabase, public navCtrl: NavController, public navParams: NavParams, private storage: Storage) {
      this.storage.get('username').then((val) => {
      if (val != null) {
        this.username= val;
      }
    });

    this.obsRef = this.db.object('/chat');
    this.obsToData = this.obsRef.valueChanges().subscribe( data => {
      var data_array= $.map(data, function(value, index) {            
        return [value];
      });

      this.messages= data_array;
    });
  }

  sendMessage() {
    this.db.list('/chat').push({
      username: this.username,
      message: this.message
    }).then( () => {
      this.message= '';
    });
  }

  ionViewWillLeave() {
    console.log('user is about to go');
    this.obsToData.unsubscribe();

    this.db.list('/chat').push({
      specialMessage: true,
      message: `${this.username} has left the room`
    })
  }

  ionViewDidLoad() {

    console.log(this.username);

    this.db.list('/chat').push({
      specialMessage: true,
      message: this.username + `has joined the room`
    })
  }
}
&#13;
&#13;
&#13;

chat.html:

&#13;
&#13;
<ion-header>

  <ion-navbar>
    <ion-title>Chat</ion-title>
  </ion-navbar>

</ion-header>


<ion-content padding>

<div id="chatMessages">
  <div *ngFor="let message of messages" [class]="message.specialMessage ? 'message special': 'message'">
    <div [class]="message.username == username ? 'innerMessage messageRight': 'innerMessage messageLeft'">
      <div class="username"> {{ message.username }} </div>
      <div class="messageContent"> {{ message.message }} </div>
    </div>
  </div>
</div>

</ion-content>

<ion-footer>
    <div id="footer">
      <ion-input type="text" [(ngModel)]= "message"> </ion-input>
      <button ion-button icon-only (click)= "sendMessage()">
      <ion-icon name="send"></ion-icon>
      </button>
    </div>
</ion-footer>
&#13;
&#13;
&#13;

0 个答案:

没有答案