Try to search your question here, if you can't find : Ask Any Question Now ?

Angular Component in Chat App closing instantly

HomeCategory: stackoverflowAngular Component in Chat App closing instantly
Avatarkundan asked 3 months ago

I’m trying to create a small messenger with an Angular PWA and a Java Server with a WebSocket connection.

I already have a chat list component in which I can see some contacts. If I click on a contact it should open up the chat window with all the messages. It opens the window and console.log tells me that it loads the correct message data from the server, but it closes the window instantly and goes back to the chat list component.

The other problem I have is that this.websocket.socket.unsubscribe(); somehow doesn’t work, which means that in every component in which I subscribed to the websocket I can’t unsubscribe anymore.

Please help, I’m getting desperate

In this method which I call in ngOnInit I load the messages from the server. If I log message.data, I can see it’s correct but after the function is executed it goes back to the chat list.

loadNewMessages() {
    console.log('refresh');
    this.websocket.socket.next(new MessageEvent('{' +
      '"action": "get_person",' +
      '"on": "message",' +
      '"attributes": {' +
      '"person_name": "' + this.chatPartner + '"' +
      '}}'
    ));
    this.websocket.messageReceived.subscribe(
      (message: MessageEvent) => {
        const res = JSON.parse(message.data);
        if (res.error) {
          console.log(res.error);
        } else if (res.messages) {
          this.tmList = [];
          res.messages.forEach(m => {
            const writer = m.from_name;
            let reader = this.websocket.Username;
            let fromMe = false;
            if (this.websocket.Username === writer) {
              reader = this.chatPartner;
              fromMe = true;
            }
            const msg = new Message(new Person(writer, ''), new Person(reader, ''), fromMe, false, m.text, new Date(m.date), false, null);
            if (!this.tmList.includes(msg)) {
              this.tmList.push(msg);
            }
          });
        }
      });
    this.sendText = '';
  }

this is my websocket implementation

import { Injectable } from '@angular/core';
import { Subject, Observer, Observable } from 'rxjs/Rx';
import { Person } from '../entities/Person';

@Injectable()
export class ObservableWebsocket {

  Username: string;
  newMessageUsernames: string[] = [];
  newMessageGroupnames: number[] = [];
  actualHost: Person = null;

  public socket: Subject<MessageEvent>;
  public messageReceived: Subject<MessageEvent> = new Subject<MessageEvent>();

  public constructor() {
    this.createWebsocket();
    this.socket.subscribe(
      (message: MessageEvent) => {
        this.messageReceived.next(message);
      });
  }

  public createWebsocket(): void {
    //let socket = new WebSocket('ws://88.117.121.8:8025/websockets/chat');
    let socket = new WebSocket('ws://localhost:8025/websocket/chat');

    let observable = Observable.create(
      (observer: Observer<MessageEvent>) => {
        socket.onmessage = observer.next.bind(observer);
        socket.onerror = observer.error.bind(observer);
        socket.onclose = observer.complete.bind(observer);
        return socket.close.bind(socket);
      }
    );

    let observer = {
      next: (data: MessageEvent) => {
        if (socket.readyState === WebSocket.OPEN) {
          socket.send(data.type);
          //socket.send(data.data);
        }
      }
    };

    this.socket = Subject.create(observer, observable);
  }
}

And this is an example where I try to unsubscribe from the websocket, which doesn’t work

login() {
    this.websocket.socket.next(new MessageEvent('{' +
      '"action": "login",' +
      '"on": "person",' +
      '"attributes": {' +
        '"person_name": "' + this.username + '"' +
      '}' +
    '}'
    ));
  }

  constructor(private router: Router, private websocket: ObservableWebsocket) { }

  ngOnInit() {
    this.websocket.messageReceived.subscribe(
      (message: MessageEvent) => {
        const res = JSON.parse(message.data);
        if (res.error) {
          console.log(res.error);
        } else {
          this.websocket.socket.unsubscribe();
          this.websocket.Username = this.username;
          this.router.navigateByUrl('/chats');
        }
      }
    );
  }
1 Answers
Best Answer
AvatarMikhail answered 3 months ago
Your Answer

11 + 11 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com