Error TS2564: Property 'stompClient' has no initializer and is not definitely assigned in the...

Discussão em 'Angular' iniciado por Александр, Novembro 7, 2024.

  1. I am working on an Angular service for connecting to a WebSocket server using STOMP protocol. The service establishes a WebSocket connection, subscribes to a topic, and processes incoming messages to update a Subject.

    In web-socket.service.ts, I encounter the following TypeScript error:

    TS2564: Property 'stompClient' has no initializer and is not definitely assigned in the constructor.


    web-socket.service.ts code:

    import { Injectable } from '@angular/core';
    import { Client, Message } from '@stomp/stompjs';
    import * as SockJS from 'sockjs-client';
    import { Subject } from 'rxjs';
    import { MusicBand } from '../models/music-band.model';

    @Injectable({
    providedIn: 'root',
    })
    export class WebSocketService {
    private stompClient: Client;
    private musicBandUpdates = new Subject<MusicBand>();

    constructor() {
    this.connect();
    }

    /**
    * Connecting to a WebSocket server.
    */
    connect() {
    this.stompClient = new Client({
    webSocketFactory: () => new SockJS('http://localhost:8080/ws'),
    connectHeaders: {},
    debug: (str: string) => {
    console.log(str);
    },
    reconnectDelay: 5000,
    heartbeatIncoming: 4000,
    heartbeatOutgoing: 4000,
    });

    this.stompClient.onConnect = (frame: any) => {
    console.log('Connected: ' + frame);
    this.stompClient.subscribe('/topic/musicbands', (message: Message) => {
    const updatedBand: MusicBand = JSON.parse(message.body);
    this.musicBandUpdates.next(updatedBand);
    });
    };

    this.stompClient.onStompError = (frame: any) => {
    console.error('Broker reported error: ' + frame.headers['message']);
    console.error('Additional details: ' + frame.body);
    };

    this.stompClient.activate();
    }

    /**
    * Get music group updates.
    */
    getMusicBandUpdates() {
    return this.musicBandUpdates.asObservable();
    }

    /**
    * Sending a message via WebSocket
    * @param destination Destination route
    * @param body Message body
    */
    sendMessage(destination: string, body: any) {
    if (this.stompClient.connected) {
    this.stompClient.publish({ destination, body: JSON.stringify(body) });
    }
    }

    /**
    * Disconnecting from WebSocket server.
    */
    disconnect() {
    if (this.stompClient) {
    this.stompClient.deactivate();
    console.log('Disconnected');
    }
    }
    }


    typescript: 5.1.3 Angular: 16.2.12

    TypeScript assumes that stompClient may not be assigned in some code paths since it’s neither optional nor initialized immediately. The property is set only when connect() is called, but TypeScript cannot verify this path in the constructor.

    Desired Outcome: To initialize stompClient correctly in a way that satisfies TypeScript and prevents any runtime issues from accessing an uninitialized WebSocket client.

    Continue reading...

Compartilhe esta Página