如何在Angular 6中使用WebSocket?Spring与Angular 6通知通信遇阻求助
Hey there! Let's get your Spring + Angular 6 WebSocket notification setup working smoothly. Import issues with those libraries usually stem from version mismatches or incorrect setup steps—let's break this down step by step.
First, let's clean up any potentially mismatched packages and install versions that play nice with Angular 6:
- Uninstall any existing problematic packages:
npm uninstall stompjs sockjs-client angular2-websocket - Install the maintained, Angular 6-friendly versions:
npm install @stomp/stompjs@5.4.4 sockjs-client@1.5.2 --save - Add TypeScript type definitions for SockJS (to avoid type errors):
npm install @types/sockjs-client --save-dev
Note: angular2-websocket is outdated and unmaintained—we'll use @stomp/stompjs instead, which is actively supported and works seamlessly with SockJS.
In your Angular service file (e.g., websocket-notification.service.ts), use these correct import paths:
import * as SockJS from 'sockjs-client'; import { Stomp } from '@stomp/stompjs';
If you still see import errors, double-check that the packages are listed in your package.json and run npm install again to ensure they're properly installed.
Here's a complete, reusable service to handle connections, subscriptions, and notifications:
import { Injectable } from '@angular/core'; import * as SockJS from 'sockjs-client'; import { Stomp } from '@stomp/stompjs'; import { BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class WebSocketNotificationService { private stompClient: any; public notificationSubject = new BehaviorSubject<any>(null); connect() { // Replace with your Spring backend's WebSocket endpoint const socket = new SockJS('http://localhost:8080/ws'); this.stompClient = Stomp.over(socket); // Disable debug logs if you don't need them this.stompClient.debug = () => {}; this.stompClient.connect({}, (frame: any) => { console.log('Connected to WebSocket:', frame); // Subscribe to your notification topic this.stompClient.subscribe('/topic/notifications', (message: any) => { const notification = JSON.parse(message.body); this.notificationSubject.next(notification); }); }, (error: any) => { console.error('WebSocket connection failed:', error); // Auto-reconnect after 5 seconds if connection drops setTimeout(() => this.connect(), 5000); }); } disconnect() { if (this.stompClient) { this.stompClient.disconnect(); console.log('Disconnected from WebSocket'); } } // Optional: Send messages to the Spring backend sendNotification(notification: any) { this.stompClient.send('/app/send-notification', {}, JSON.stringify(notification)); } }
Make sure your Spring setup is correctly configured to handle WebSocket connections:
WebSocket Configuration Class
import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { // Enable simple broker for notification topics config.enableSimpleBroker("/topic"); // Prefix for messages sent to backend controllers config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { // Endpoint matching what we use in Angular, with SockJS fallback registry.addEndpoint("/ws").withSockJS(); } }
Notification Controller
import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.stereotype.Controller; @Controller public class NotificationController { // Listen for messages sent to /app/send-notification @MessageMapping("/send-notification") // Broadcast the message to all subscribers of /topic/notifications @SendTo("/topic/notifications") public Notification broadcastNotification(Notification notification) { return notification; } // Simple Notification DTO public static class Notification { private String title; private String content; // Getters and Setters public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } } }
Inject the service into a component to start listening for notifications:
import { Component, OnInit, OnDestroy } from '@angular/core'; import { WebSocketNotificationService } from './websocket-notification.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit, OnDestroy { currentNotification: any; constructor(private wsService: WebSocketNotificationService) {} ngOnInit() { this.wsService.connect(); // Subscribe to incoming notifications this.wsService.notificationSubject.subscribe(notification => { if (notification) { this.currentNotification = notification; console.log('New notification:', this.currentNotification); // Add your UI update logic here (e.g., show a toast) } }); } ngOnDestroy() { this.wsService.disconnect(); } }
- "Cannot find module" errors: Verify that the packages are listed in
package.jsonand runnpm installagain. If type errors persist, ensure@types/sockjs-clientis installed. - Connection failures: Check that your Spring backend is running, the endpoint URL matches in both Angular and Spring, and there are no CORS issues (add CORS configuration in Spring if needed).
- Stomp client not connecting: Use the
debugmethod (uncommented in the service) to see detailed connection logs and identify issues.
内容的提问来源于stack exchange,提问作者BOUABDELLAH Imane

