Angular 4中的Websocket和RxJS的困惑 [英] Websocket in Angular 4 and RxJS confusion
本文介绍了Angular 4中的Websocket和RxJS的困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试通过websockets和Angular 4学习RxJS,并找到了一个很好的示例
I am trying to learn RxJS with websockets and Angular 4, and found a good example here. I'm hoping someone can help explain the example as a few things are confusing.
他们创建了2个Angular服务,即Websocket服务:
They have created 2 Angular services, the Websocket Service:
import { Injectable } from '@angular/core';
import * as Rx from 'rxjs/Rx';
@Injectable()
export class WebsocketService {
constructor() { }
private subject: Rx.Subject<MessageEvent>;
public connect(url): Rx.Subject<MessageEvent> {
if (!this.subject) {
this.subject = this.create(url);
console.log("Successfully connected: " + url);
}
return this.subject;
}
private create(url): Rx.Subject<MessageEvent> {
let ws = new WebSocket(url);
let observable = Rx.Observable.create(
(obs: Rx.Observer<MessageEvent>) => {
ws.onmessage = obs.next.bind(obs);
ws.onerror = obs.error.bind(obs);
ws.onclose = obs.complete.bind(obs);
return ws.close.bind(ws);
})
let observer = {
next: (data: Object) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(data));
}
}
}
return Rx.Subject.create(observer, observable);
}
}
和聊天服务:
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/Rx';
import { WebsocketService } from './websocket.service';
const CHAT_URL = 'ws://echo.websocket.org/';
export interface Message {
author: string,
message: string
}
@Injectable()
export class ChatService {
public messages: Subject<Message>;
constructor(wsService: WebsocketService) {
this.messages = <Subject<Message>>wsService
.connect(CHAT_URL)
.map((response: MessageEvent): Message => {
let data = JSON.parse(response.data);
return {
author: data.author,
message: data.message
}
});
}
}
我对此有很多疑问:
- 为什么必须创建2个服务?主题不能是观察者并且是可观察的(因此它可以直接中继消息而无需第二个Chat服务)吗?解决创建2个服务的问题是什么?
- 在Websocket服务中,为什么.create函数调用的最后一行返回ws.close.bind(ws)?那是做什么的?
- 如何断开网络套接字的连接?有没有办法使其重新连接?
- 服务应如何关闭/处置websocket?
推荐答案
- 可重用性
- 因此您可以取消订阅observable,从而关闭连接 在您提供的示例中,
-
可能类似于(当您有chatService实例时)
- Reuseability
- so you can unsubscribe from observable which in turn closes the connection
in the example you gave it would probably be something like (when you have a instance of chatService)
let sub = chatService.messages.subscribe(()=>{
// do your stuff
});
// some where in your code
sub.unsubscribe() // this will close the connection
已经在3分内回答
already answered in 3
这篇关于Angular 4中的Websocket和RxJS的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文