我正在开发一个 Angular 服务,用于使用 STOMP 协议连接到 WebSocket 服务器。该服务建立 WebSocket 连接、订阅主题并处理传入消息以更新主题。
在 web-socket.service.ts 中,我遇到以下 TypeScript 错误: TS2564:属性“stompClient”没有初始值设定项,并且未在构造函数中明确分配。
web-socket.service.ts 代码:
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');
}
}
}
打字稿:5.1.3 角度:16.2.12
TypeScript 假设 stompClient 可能不会在某些代码路径中分配,因为它既不是可选的也不是立即初始化的。该属性仅在调用 connect() 时设置,但 TypeScript 无法在构造函数中验证此路径。
期望的结果:以满足 TypeScript 的方式正确初始化 stompClient 并防止任何运行时问题访问未初始化的 WebSocket 客户端。
你只需要断言该值将被定义,你可以使用
!:
来解决这个错误。
@Injectable({
providedIn: 'root',
})
export class WebSocketService {
private stompClient!: Client; // <- changed here!