首页 > 解决方案 > Angular 5 和 Rxjs - 订阅多次触发

问题描述

尝试使用 Angular 和 RxJs 处理 SocketIO websockets。最初它可以工作,但是当我在应用程序中导航并加载和卸载组件时,会为 SocketIO 消息主题创建多个订阅。这导致数据在组件上被多次处理。

我最初的解决方案是在 ngOnDestroy 事件中取消订阅主题,但这完全破坏了主题,并且当我在创建新订阅时导航回包含组件的页面时,它不再起作用。

websocket.service

    @Injectable()
    export class WebsocketService {

      private socket;

      constructor() { } 

      public connect(): Rx.Subject<MessageEvent> {
        this.socket = io(WS_URL)

        let observable = new Observable(observer => {
          this.socket.on('message', (data) => {
            observer.next(data)
          })  
          return () => {
            this.socket.disconnect();
          }   
        })  

        let observer = { 
          next: (data: Object) => {
            this.socket.emit('message', JSON.stringify(data));
          }   
        }   

        return Rx.Subject.create(observer, observable)
      }
    }

聊天服务

@Injectable()
export class ChatService {
  public messages: Subject<any>;
  public shared: Observable<any>;

  constructor(
    private ws: WebsocketService  
  ) { 
    this.messages = <Subject<any>>ws
      .connect()
      .map((response : any) => {
        console.log("Recv " + response.type)
        return response
      })  

    this.shared = this.messages.share();
  }

  sendMessage(msg) {
    this.messages.next(msg)
  }

}

仪表板.组件

export class DashboardComponent implements OnInit, OnDestroy {
  subscription_obs: any;

  constructor(
    private chat: ChatService
  ) { } 

  ngOnInit() {
    this.subscription_obs = this.chat.shared.subscribe(msg => {
      console.log("Dashboard subscription fire!")
    })  
  }

  ngOnDestroy() {
    this.subscription_obs.unsubscribe()
  }
}

标签: angularsocket.iorxjs

解决方案


推荐阅读