export class SocketsService {
ws: any;
messages: Subject<any>;
private connectionSubject: Subject<MessageEvent>;
constructor(
@Inject('wsServerUrl') private wsUrl : string
) {
this.initConnection();
}
public initConnection() {
this.messages= new Subject<any>();
this.connectionSubject = this.wsCreate(this.wsUrl);
if (typeof this.ws!== 'undefined' && this.ws.readyState !== 0 && this.ws.readyState !== 1) {
this.connectionSubject = this.wsCreate(this.wsUrl);
}
this.ws.onmessage = e => {
const response = e.data;
return this.orders.next(response);
};
this.ws.onclose = e => console.log('client disconnected ');
}
send(value: string) {
this.ws.send(value);
}
closeConnection() {
this.ws.close(1000, 'disconnect');
this.ws = undefined;
}
private wsCreate(url): Subject<any> {
this.ws= new WebSocket(url);
const observable = new Observable((obs: Observer<string>) => {
this.ws.onmessage = obs.next.bind(obs);
this.ws.onerror = obs.error.bind(obs);
this.ws.onclose = obs.complete.bind(obs);
return this.ws.close.bind(this.ws);
});
const observer = {
next: (data: object) => {
if (this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(data));
}
}
};
return Subject.create(observer, observable);
}
}
используя тему, вы можете подписаться на сообщения в любом компоненте. Чтобы создать соединение, вам нужно внедрить этот сервис в компонент (например, app.component). Затем вы можете отправлять сообщения, используя отправить метод обслуживания
прослушивать сообщения в компоненте:
this.subscription = this.socketsService.messages.subscribe((message: string) => {
// do something
});