我正在尝试建立套接字连接。但是我得到了上面的错误。我正在尝试使用其他端点来实现https://tutorialedge.net/typescript/angular/angular-websockets-tutorial/。
socket.service.ts
import { Injectable } from '@angular/core';
import * as Rx from 'rxjs/Rx';
@Injectable({
providedIn: 'root'
})
export class SocketService {
constructor() { }
private subject: Rx.Subject<MessageEvent>;
public connect(url): Rx.Subject<MessageEvent> {
if (!this.subject) {
this.subject = this.create(url);
console.log("Successfully connected: " + url);
}
return this.subject;
}
private create(url): Rx.Subject<MessageEvent> {
let ws = new WebSocket(url);
let observable = Rx.Observable.create(
(obs: Rx.Observer<MessageEvent>) => {
ws.onmessage = obs.next.bind(obs);
ws.onerror = obs.error.bind(obs);
ws.onclose = obs.complete.bind(obs);
return ws.close.bind(ws);
})
let observer = {
next: (data: Object) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(data));
}
}
}
return Rx.Subject.create(observer, observable);
}
}
chat.service.ts
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/Rx';
import {SocketService} from '../services/socket.service';
let ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
let ws_path = ws_scheme + '://' + window.location.host +
"/api/chat/stream/";
const CHAT_URL = ws_path;
export interface Message {
author: string,
message: string
}
@Injectable({
providedIn: 'root'
})
export class UploadSocketService {
public messages: Subject<Message>;
constructor(wsService: SocketService) {
this.messages = <Subject<Message>>wsService
.connect(CHAT_URL)
.map((response: MessageEvent): Message => {
let data = JSON.parse(response.data);
return {
author: data.author,
message: data.message
}
});
}
}
我在 socket.service.ts 中遇到了错误,其中的代码是ws = new WebSocket(url);
如何解决这个问题?
答案 0 :(得分:1)
如果您使用angular cli代理获取/ api /进入后端,则需要将ws: true
添加到代理配置中,否则它将无法创建websocket连接。
{
"/api/": {
"target": "http://localhost:8080",
"secure": false
"ws":true
}
}