使用RxJs和WebSockets我创建了一些应该从服务器接收数据的服务,并将其发送给我程序中服务的订阅者。当我只有1个服务时,没有问题,但在创建第二个服务后,第一个服务不再收到响应。我该如何确定呢?
这是我的WebSocket服务:
import { Injectable } from '@angular/core';
import * as Rx from 'rxjs/Rx';
@Injectable()
export class WebSocketService {
private subject: Rx.Subject<MessageEvent>;
public connect(url): Rx.Subject<MessageEvent> {
if (!this.subject) {
this.subject = this.create(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 AUCTION_URL = 'ws://localhost:9999';
export interface Countdown {
days: number,
hours: number,
minutes: number,
seconds: number
}
@Injectable()
export class CountdownService {
public countdowns: Subject<Countdown>;
constructor(wsService: WebSocketService) {
this.countdowns = <Subject<Countdown>>wsService
.connect(AUCTION_URL)
.map((response: MessageEvent): Countdown => {
let data = JSON.parse(response.data);
return {
days: data.days,
hours: data.hours,
minutes: data.minutes,
seconds: data.seconds
}
});
}
}
其他服务的实现方式与倒计时服务相同,但与其他变量相同。
感谢任何帮助,谢谢。
答案 0 :(得分:1)
该服务是否跨多个组件使用?我会检查该服务是否只被实例化一次。
您还可以通过将share操作符添加到observable create:
来确保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);
}).share()