angular - 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()
}
}
解决方案
推荐阅读
- angular - Angular 在返回数据之前等待订阅完成
- reactjs - 如何在 reducer redux 中放置 2 个不同的有效负载?
- c# - 我是通过继承来实现系统的,但是有一个模棱两可的部分
- python - “元组”对象没有属性“火车”
- powershell - Get-childitem 不适用于 foreach 循环
- python - Python zeep 更改 SOAP 正文中签名的前缀
- node.js - 在对我的 node.js 应用程序的多个请求中重用 AWS.S3 的同一实例
- android - 应用程序被杀死时未触发 Android WorkManager 定期任务
- javascript - 赛普拉斯从内部获取价值
- r - 如何通过 testthat 测试使用 sink(type = "message") 的函数