typescript - Hata TS2564: 'stompClient' özelliğinin bir başlatıcısı yok ve Angular WebSocket Servisindeki yapıcıda kesin olarak atanmış değil
STOMP protokolünü kullanarak bir WebSocket sunucusuna bağlanan bir Angular servisi üzerinde çalışıyorum. Servis bir WebSocket bağlantısı kurar, bir konuya abone olur ve gelen mesajları bir Subject'i güncellemek için işler.
web-socket.service.ts dosyasında, aşağıdaki TypeScript hatasıyla karşılaşıyorum:
TS2564: Property 'stompClient' has no initializer and is not definitely assigned in the constructor.
web-socket.service.ts kodu:
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, stompClient'in bazı kod yollarında atanamayabileceğini varsayar çünkü bu ya isteğe bağlı değildir ya da hemen başlatılmaz. Özellik yalnızca connect() çağrıldığında ayarlanır, ancak TypeScript yapıcıda bu yolu doğrulayamaz.
İstenen Sonuç: TypeScript'i tatmin eden ve başlatılmamış bir WebSocket istemcisine erişimden kaynaklanabilecek çalışma zamanı sorunlarını önleyen bir şekilde stompClient'i doğru şekilde başlatmak.
Cevap #1
Sadece değerin tanımlı olacağını belirtmeniz gerekiyor, bu hatayı çözmek için !: kullanabilirsiniz.
@Injectable({
providedIn: 'root',
})
export class WebSocketService {
private stompClient!: Client; // <- changed here!
