socket.io вызывает несколько экземпляров при последующих вызовах - PullRequest
0 голосов
/ 04 ноября 2019

Я пытаюсь создать функцию запроса дружбы в моем проекте MEAN-стека, который в режиме реального времени использует socket.io

, вот мой код:

Клиентский компонент

import { Component, OnInit } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
import { AppService } from '../../services/app.service';
import { FriendListSocketService } from './../../services/friend-list-socket.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-user-friends',
  templateUrl: './user-friends.component.html',
  styleUrls: ['./user-friends.component.css'],
  // providers: [FriendListSocketService]
})
export class UserFriendsComponent implements OnInit {


  public userList:any=[];
  public userId:String=''; //userId of the logged in user.

  constructor(
    public appService:AppService,
    public friendSocketService:FriendListSocketService,
    public cookies:CookieService,
    public router:Router) { }

  ngOnInit() {
    this.userId=this.cookies.get('userId');
    this.getOtherUsers(this.userId); //loading the other users in the add friends page.
    this.listLoader(this.userId); //informs the view if any request comes from friend.
  }

  public getOtherUsers:any=(userId)=>{
    this.appService.userList(userId).subscribe((apiResponse)=>{
      console.log(apiResponse);
      this.userList=[];
      if(apiResponse.status===200){
        this.userList=apiResponse.data;
      }else {
        this.toastr.warning(apiResponse.message);
      }
    })
  } //this func is to get the users who are not friends from the backend. call this whenever the list is needed.

  public addFriend(friendId){

    this.appService.addFriend(this.userId, friendId).subscribe((apiResponse)=>{
      console.log(apiResponse);
      if(apiResponse.status===200){
        this.getOtherUsers(this.userId);
        let data={
          action:'add',
          message:'Add Request sent',
          sender:this.userId,
          receipient:friendId
        }
        this.friendSocketService.notifyFriend(data);
      }else {
        this.toastr.warning(apiResponse.message);
      }
    });

  }

  public listLoader:any=(userId)=>{
    this.friendSocketService.listReload(userId).subscribe((apiResponse)=>{
      if(apiResponse.action==='add'){
        console.log("list Loader called.");
        this.getOtherUsers(userId);
      }else if(apiResponse.action==='delete'){
        console.log("Request Deleted");
        this.getOtherUsers(userId);
      }

    })
  }
}

на стороне клиента - сервис

import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { CookieService } from 'ngx-cookie-service';

// @Injectable()

@Injectable({
  providedIn: 'root'
})
export class FriendListSocketService {

  private url = "http://localhost:3000/";
  private socket;

  constructor(public http:HttpClient, public cookie:CookieService) { 
    this.socket=io(this.url); // connection is being created. i.e the handshake is happening here.
    console.log("socket connected",data);
  }

  public listReload=(userId)=>{
    return Observable.create((observer)=>{
      this.socket.on(userId,(data)=>{
        observer.next(data);
      })
    })
  }//this shall listen to calls from backend on userId if any friend statuses change,then it shall inform the component.

  public notifyFriend=(data)=>{
    this.socket.emit('notifyFriend',data);
  }
}

на стороне сервера

let setServer = (server) => {

    let io = socketio.listen(server);

    let myIo = io.of('/');

    myIo.on('connection', (socket) => {

        console.log("on connection--functions are ready");

        socket.on('notifyFriend', (data) => {      //here the friendId is received to whom the message has to be sent.

            if (data.action === 'add') {
                let response = {
                    message: 'Friend Request Received',
                    action: 'add'
                }
                myIo.emit(data.receipient, response);
            } else if (data.action === 'delete') {
                let response = {
                    message: 'Friend Request Received',
                    action: 'delete'
                }
                myIo.emit(data.receipient, response);
            } else if (data.action === 'accept') {
                let response = {
                    message: 'Friend Request Received',
                    action: 'accept'
                }

                myIo.emit(data.receipient, response);
            }

        })
    })
}

Проблемавсякий раз, когда я пытаюсь сделать межсетевой обмен сообщениями, сообщения становятся все больше и больше. пример: когда я пытаюсь принять / удалить запрос, я получаю несколько сообщений на стороне получателя. Пожалуйста, помогите мне, поскольку я не могу понять, как настраиваются несколько запросов, хотя я звоню в службу только один раз.

Примечание: ранее я также пытался предоставить услугу в компоненте, но там я тоже получал одни и те же множественные вызовы. find here the pic of console

здесь user-home.component.ts и user-friends.component.ts вызываются при наличиислушатель в user-home также, и служба инициируется в самом корне.

...