如何在Angular12中做一个简单的rxjs/webSocket服务?

How to make a simple rxjs/webSocket service in Angular 12?

我试图在 Angular12 中创建一个非常简单的 websocket 服务,但我似乎找不到任何可用的示例。我已经尝试了很多教程,包括 this 最近的一个,但即使他们给出的例子似乎也不适合我(我已经尝试自己实现它,并且还尝试 git 克隆他们的例子。都没有工作)

我正在尝试通过移植一个旧的 AngularJS 应用程序来学习 Angular12,我在其中使用了 websockets 和 ng-websocket 包。 RxJS 似乎是用于 websockets 的更流行的库之一,所以我选择了它。到目前为止,我只能使以下示例正常工作:

// app.component.ts
import { webSocket } from 'rxjs/webSocket';
import {environment} from '../environments/environment';
...

const subject = webSocket(environment.backendWebsocketEndpoint)
subject.subscribe(msg => {
    console.log('Message from server?', msg)
  },
  err => {
    console.log('Error with websocket connection:', err)
  },
  () => {
    console.log('complete')
  }
)
subject.next('my message');

如何将这个简单的示例变成可以在我的组件中使用的服务?我不想经常必须创建主题变量并在它们上调用 .subscribe 因为这会打开一个新的 websocket 连接并且整个应用程序可能只需要 1 个共享连接就可以工作。

// I'm also having trouble sending JS objs as the data as well. They should be getting JSON.parsed
// and sent but doing something like this gives an error:
//
// var payload = {"action": "whatever", "message": "my message"}
// console.log(payload)
// console.log(JSON.stringify(payload)) // Do I have to stringify first????
// subject.next(payload);
// ^ GIVES ERROR
// Error with websocket connection: SyntaxError: Unexpected token m in JSON at position 0
// adding deserializer: msg => msg to the subject config fixes this but idk why. 

有关更多上下文,我正在为我的后端使用 AWS api 网关 websocket,尽管我想这个 rxjs 库可以与任何 websocket 服务器一起使用。

我认为最简单的示例如下所示:

export class WebSocketService {
  private socket$  = new webSocket(url);
  public messages$ = this.socket$.asObservable();

  public sendMessage(msg: any) {
    this.socket$.next(msg);
  }
}

解决您的问题:

...because that opens a new websocket connection and the entire app could probably work off of just 1 shared connection.

这不是问题,RxJs webSocket 只会使用单个连接。来自 the docs:

When WebSocketSubject is subscribed, it attempts to make a socket connection, unless there is one made already. This means that many subscribers will always listen on the same socket, thus saving resources

是的,您需要在发送消息之前进行字符串化:

...bear in mind that this value will not be serialized beforehand. Because of This, JSON.stringify will have to be called on a value by hand, before calling next