在 Angular 中连接 WebSocket
Posted
技术标签:
【中文标题】在 Angular 中连接 WebSocket【英文标题】:Connecting a WebSocket in Angular 【发布时间】:2020-03-31 13:53:19 【问题描述】:我在 Node 中有 WebSocket 连接,它工作正常。 现在我想通过 rxjs websocket 在 Angular 中使用它,但我不知道如何解决连接问题。
const WebSocket = require('ws');
const ws = new WebSocket('wss://example.com');
ws.on('open', function open()
// on connection, send our authentication request
ws.send(JSON.stringify(action: 'auth', key: apiKey, secret: apiSecret));
);
ws.on('close', function close()
console.log('disconnected');
);
ws.on('message', function incoming(data)
console.log(data)
var msg = JSON.parse(data);
if (msg.type === 'status' && msg.status === 'authenticated')
// if we got authentication confirmation, send subscribe event to the server
ws.send(JSON.stringify(action: 'subscribe', buckets: ['exampleBucket']));
);
【问题讨论】:
【参考方案1】:监听来自服务器的消息
import webSocket from "rxjs/webSocket";
const subject = webSocket('wss://example.com');
subject.subscribe(
msg => console.log('message received: ' + msg), // Called whenever there is a message from the server.
err => console.log(err), // Called if at any point WebSocket API signals some kind of error.
() => console.log('complete') // Called when connection is closed (for whatever reason).
);
向服务器推送消息
import webSocket from "rxjs/webSocket";
const subject = webSocket('wss://example.com');
subject.subscribe();
// Note that at least one consumer has to subscribe to the created subject - otherwise "nexted" values will be just buffered and not sent,
// since no connection was established!
subject.next(message: 'some message');
// This will send a message to the server once a connection is made. Remember value is serialized with JSON.stringify by default!
subject.complete(); // Closes the connection.
subject.error(code: 4000, reason: 'I think our app just broke!');
// Also closes the connection, but let's the server know that this closing is caused by some error.
【讨论】:
以上是关于在 Angular 中连接 WebSocket的主要内容,如果未能解决你的问题,请参考以下文章
Angular.js HTTP 连接 - 更改 URL - 破坏 Angular
在 Angular 和 rxjs 中重新连接 websocket?
在开发环境中使用 Angular CLI 连接 express.js