尝试使用Angular和RxJs处理SocketIO websocket。最初它可以工作,但是当我在应用程序中导航并且加载和卸载了组件时,会为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)
}
}
dashboard.component
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()
}
}