Why is my Angular UI not working when injecting websocket?

Discussão em 'Angular' iniciado por Henk Fransen, Janeiro 26, 2025.

  1. Henk Fransen

    Henk Fransen Guest

    When I add the connect method, my button is no longer working. When i comment the method out, the button start working and the UI shows changes. But as soon as the connect method is implemented, the UI is no longer updating the values. in the console i see the websocket working and receiving messages. Why is my button no longer working when adding the websocket connection?

    import { Injectable } from '@angular/core';
    import { Observable, Subject } from 'rxjs';
    import SockJS from 'sockjs-client';
    import { Client } from '@stomp/stompjs';

    @Injectable({
    providedIn: 'root',
    })
    export class WebSocketService {
    private stompClient: Client | null = null; // Use Client from StompJS for better typings
    private messageSubject = new Subject<string>();

    constructor() {}

    public connect(): void {
    // Initialize SockJS and Stomp client
    const socket = new SockJS('http://localhost:8082/ws');
    this.stompClient = new Client({
    webSocketFactory: () => socket,
    debug: (str) => console.log(str), // Optional: Log debug info
    reconnectDelay: 5000, // Attempt to reconnect every 5 seconds
    });

    // On successful connection
    this.stompClient.onConnect = () => {
    console.log('WebSocket connected');
    this.stompClient?.subscribe('/topic/notifications', (message) => {
    this.messageSubject.next(message.body);
    });
    };

    // Handle connection errors
    this.stompClient.onStompError = (frame) => {
    console.error('Stomp error:', frame);
    };

    // Activate the connection
    this.stompClient.activate();
    }

    public disconnect(): void {
    if (this.stompClient?.connected) {
    this.stompClient.deactivate();
    console.log('WebSocket disconnected');
    }
    }

    public getMessages(): Observable<string> {
    return this.messageSubject.asObservable();
    }
    }



    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { Subscription } from 'rxjs';
    import {WebSocketService} from "./websocket.service";

    @Component({
    selector: 'app-notifications',
    template: `
    <div *ngFor="let message of messages">
    <span>haha</span>
    {{ message }}
    </div>
    <div *ngFor="let message of items">
    <span>goal</span>
    {{ message }}
    </div>
    <button (click)="addItem()">Add item</button>
    `,
    })
    export class NotificationsComponent implements OnInit, OnDestroy {
    private subscription!: Subscription; // To manage and clean up the subscription
    public messages: string[] = [];
    items: string[] = []; // Array to hold the items

    addItem(): void {
    this.items.push("ADDED");
    }

    constructor(private webSocketService: WebSocketService) {}

    ngOnInit(): void {
    // Establish the WebSocket connection
    this.webSocketService.connect();

    // Subscribe to WebSocket messages
    this.subscription = this.webSocketService.getMessages().subscribe((message) => {
    console.log('Received message:', message);
    this.messages.push(message); // Add the message to the list
    });
    }

    ngOnDestroy(): void {
    // Unsubscribe and disconnect to avoid memory leaks
    if (this.subscription) {
    this.subscription.unsubscribe();
    }
    this.webSocketService.disconnect();
    }
    }


    Because of the connection, the code is no longer working. Why?

    I tried to comment out the content of the connect method and it works:

    public connect(): void {
    // // Initialize SockJS and Stomp client
    // const socket = new SockJS('http://localhost:8082/ws');
    // this.stompClient = new Client({
    // webSocketFactory: () => socket,
    // debug: (str) => console.log(str), // Optional: Log debug info
    // reconnectDelay: 5000, // Attempt to reconnect every 5 seconds
    // });
    //
    // // On successful connection
    // this.stompClient.onConnect = () => {
    // console.log('WebSocket connected');
    // this.stompClient?.subscribe('/topic/notifications', (message) => {
    // this.messageSubject.next(message.body);
    // });
    // };
    //
    // // Handle connection errors
    // this.stompClient.onStompError = (frame) => {
    // console.error('Stomp error:', frame);
    // };
    //
    // // Activate the connection
    // this.stompClient.activate();
    }



    I Dont see why it works when I uncomment the connection. Please help.

    Continue reading...

Compartilhe esta Página