我在socket.io上遇到了Angular服务问题。服务推送数据仅以其他方式查看。但是我的问题是,如何创建可观察的。例如,应该是一个,还是每个订阅新的Observable?
第一个选项
export class MessageService {
socket: SocketIOClient.Socket;
observable: Observable<any>;
subject: Subject<any>;
constructor() {
this.subject = new Subject();
this.observable = new Observable<any>(this.subscribe.bind(this));
}
init() {
if (!this.socket) {
this.socket = io('http://localhost:3000');
this.socket.on('message', (res) => {
this.subject.next(res);
});
}
}
getMessage(): Observable<any> {
this.init();
return this.observable;
}
private subscribe(subscriber: Subscriber<any>) {
this.subject.subscribe(subscriber);
}
}
第二个选项
export class MessageService {
socket: SocketIOClient.Socket;
observable: Observable<any>;
subject: Subject<any>;
constructor() {
this.subject = new Subject();
}
init() {
if (!this.socket) {
this.socket = io('http://localhost:3000');
this.socket.on('message', (res) => {
this.subject.next(res);
});
}
}
getMessage(): Observable<any> {
this.init();
return new Observable<any>(subscriber => {
this.subject.subscribe(subscriber);
});
}
}
哪个选项是最佳,更快,更安全的方式。 还是我误解了有关可观察物的某些内容?