While attempting a socket connection, an error popped up. I am following this tutorial on tutorialedge.net but using a different endpoint for implementation.
socket.service.ts
import { Injectable } from '@angular/core';
import * as Rx from 'rxjs/Rx';
@Injectable({
providedIn: 'root'
})
export class SocketService {
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);
}
}
chat.service.ts
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/Rx';
import {SocketService} from '../services/socket.service';
let ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
let ws_path = ws_scheme + '://' + window.location.host +
"/api/chat/stream/";
const CHAT_URL = ws_path;
export interface Message {
author: string,
message: string
}
@Injectable({
providedIn: 'root'
})
export class UploadSocketService {
public messages: Subject<Message>;
constructor(wsService: SocketService) {
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
}
});
}
}
An issue arises in the socket.service.ts file at the line where it has let ws = new WebSocket(url);
Any suggestions on resolving this?