1

my messages.ts page is parent and chat-room.ts is child page. There is no problem when I enter messages page but when i select any user for chat and I go to the chat room and create a new message , The person I am talking to is added one more time into the array.How can i fix this?

First enter message page = https://prnt.sc/uviwvo

second when i talk e.g"Tosun" user = https://prnt.sc/uvixxe

Finnaly when i come back (here is a problem) added once again into array =https://prnt.sc/uviyl3

message.page.ts:

import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { NavController } from '@ionic/angular';
import * as firebase from 'firebase/app';
import { Subscriber } from 'rxjs';
@Component({
  selector: 'app-messages',
  templateUrl: './messages.page.html',
  styleUrls: ['./messages.page.scss'],
})
export class MessagesPage implements OnInit {
  userInfo : Array<any> = []
  

  constructor(private db : AngularFireDatabase,private NavCtrl : NavController) { }

   ngOnInit() {
      firebase.auth().onAuthStateChanged(user=> {
      
      if (user) {

        this.db.database.ref('users/'+user.uid+"/messages").once("value",snapshot=>snapshot.forEach(a=>{
          console.log("girdi")
          this.db.object('users/'+a.key).snapshotChanges().subscribe(l => {
           this.userInfo.push({key:a.key,name:l.payload.child("name").val(),pp:l.payload.child("pp").val()})
          })
        }))
      } else {
      }
      
    });
    
  }
 
  goChat(key){
    this.NavCtrl.navigateForward("main/tabs/message/chat/"+key,{ animated: true, animationDirection: 'forward' })
  }
}

chat-room.page.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { ActivatedRoute } from '@angular/router';
import { IonContent } from '@ionic/angular';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs';
import { NavController } from '@ionic/angular';
import {map } from 'rxjs/operators'
@Component({
  selector: 'app-chat-room',
  templateUrl: './chat-room.page.html',
  styleUrls: ['./chat-room.page.scss'],
})
export class ChatRoomPage implements OnInit {
  @ViewChild(IonContent, {read: IonContent, static: false}) content: IonContent;
  messages: Observable<any[]>;
  myUid : any
  who : any
  message :string = ""
  pp:any
  name:any
  constructor(private route: ActivatedRoute,private db : AngularFireDatabase,private NavCtrl : NavController) { }

  ngOnInit() {
    this.route.paramMap.subscribe(paramMap=>{
      this.who=paramMap.get('uid')
      console.log(this.who)
     this.name =  this.db.object('/users/' + this.who + "/name").snapshotChanges().pipe(map(ch=>ch.payload.val() ));
     this.pp =  this.db.object('/users/' + this.who + "/pp").snapshotChanges().pipe(map(ch=>ch.payload.val() ));
    })
    
    firebase.auth().onAuthStateChanged(user=> {
      
      if (user) {
        this.myUid = user.uid
        this.messages = this.db.list('/users/'+user.uid+"/messages/"+this.who+"/chat").valueChanges();
        
      } else {
      }
    });
    
   
    this.scrollToBottomOnInit();

  }
  sendMessage(){
    
    var chatId =this.db.createPushId();
    firebase.auth().onAuthStateChanged(user=> {
      if (user) {
        this.db.object('/users/' + user.uid+"/messages/"+this.who+"/chat/"+chatId).update({
          message : this.message,
          who : user.uid

        }).then(a=>
          this.db.object("/users/"+this.who+"/messages/"+user.uid+"/chat/"+chatId).update({
            message : this.message,
            who : user.uid
          }).then(x=>this.message="")
          )
        
      }
    

  })
 this.scrollToBottomOnInit();
  
}
scrollToBottomOnInit() {
  setTimeout(() => {
      if (this.content.scrollToBottom) {
          this.content.scrollToBottom(400);
      }
  }, 500);
}
back(){
this.NavCtrl.navigateBack("/main/tabs/message");
}
}

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
zafer
  • 407
  • 1
  • 4
  • 16

1 Answers1

1

You need to refresh the userInfo list when you back again. The same UserInfo will always push in here.

this.userInfo.push({key:a.key,name:l.payload.child("name").val(),pp:l.payload.child("pp").val()})

You can change your ngOnInit()

ngOnInit() {
      firebase.auth().onAuthStateChanged(user=> {
      
      if (user) {

        // Add this line.
        this.userInfo = [];

        this.db.database.ref('users/'+user.uid+"/messages").once("value",snapshot=>snapshot.forEach(a=>{
          console.log("girdi")
          this.db.object('users/'+a.key).snapshotChanges().pipe(take(1)).subscribe(l => {
           this.userInfo.push({key:a.key,name:l.payload.child("name").val(),pp:l.payload.child("pp").val()})
          })
        }))
      } else {
      }
      
    });
    
  }
Akif
  • 7,098
  • 7
  • 27
  • 53