首页 > 解决方案 > 如何在网络工作者中以角度使用 RxJS websocket

问题描述

我已经在我的项目中实现了 websocket,但是浏览器性能非常慢,有时它也会冻结浏览器/浏览器选项卡。所以考虑在 web worker 中使用 websocket。如何在我的项目中将以下代码与 web worker 一起使用。

**.service.ts**

 connect(): Observable<any> {
  return of(wsURL).pipe(
    map(apiUrl => apiUrl.replace(/^https/, 'wss') + '/stream'),
    switchMap(wsUrl => {
      if (this.connection$) {
        return this.connection$;
      } else {
        this.connection$ = webSocket(wsUrl);
        return this.connection$;
      }
    })
  );

  closeConnection() {
    if (this.connection$) {
      this.connection$.complete();
      this.connection$ = null;
    }
  }

**component.ts**

ngOnInit() {
  this.webSocket.connect().pipe(
    takeUntil(this.destroyed$)
  ).subscribe(messages => this.messages.push(messages));
}

ngOnDestroy() {
  this.destroyed$.next();
}

标签: websocketrxjsangular8

解决方案


推荐阅读