You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中WebSocket未发起连接请求的问题排查求助

Fixes for Angular RxJS WebSocket Connection Not Initiating

1. Subscribe to the WebSocketSubject (Critical!)

RxJS WebSocketSubject is a cold observable—it won't start the connection until you subscribe to it. Your code creates the socket$ instance but never triggers the connection, which explains the lack of network/console activity.

Update your service to subscribe to the subject, and add error handling to catch connection issues:

constructor(private http: HttpClient) {
  console.log("Connect to WebSocket");
  // Subscribe to trigger the WebSocket connection
  this.socket$.subscribe({
    next: (msg) => console.log('Received:', msg),
    error: (err) => console.error('WebSocket error:', err),
    complete: () => console.log('Connection closed')
  });
}

2. Validate the Environment URL

Ensure environment.websocket_url is set to ws://localhost:3000 (not http://—using HTTP instead of WS will break the WebSocket handshake).

3. Configure CORS on Your Go Server

Browsers enforce CORS restrictions (Postman does not). If your Angular app runs on a different port (e.g., http://localhost:4200), your Go server must allow cross-origin WebSocket requests.

Example CORS setup for Go's gorilla/websocket library:

func serveWs(w http.ResponseWriter, r *http.Request) {
  // Set CORS headers
  w.Header().Set("Access-Control-Allow-Origin", "http://localhost:4200")
  w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
  
  // Handle preflight OPTIONS request
  if r.Method == "OPTIONS" {
    w.WriteHeader(http.StatusOK)
    return
  }
  
  // Upgrade to WebSocket with origin check
  upgrader := websocket.Upgrader{
    CheckOrigin: func(r *http.Request) bool {
      return r.Header.Get("Origin") == "http://localhost:4200"
    },
  }
  conn, err := upgrader.Upgrade(w, r, nil)
  if err != nil {
    log.Println(err)
    return
  }
  // ... rest of your WebSocket logic
}

4. Remove Unused Socket.IO Code

The old socket = io(...) line is irrelevant to your WebSocket setup—delete it to avoid confusion or unintended side effects.

After applying these changes, check the browser console for connection logs or error messages to diagnose any remaining issues.

内容的提问来源于stack exchange,提问作者Alms

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 04:10:09