user9040429
user9040429

Reputation: 720

Using web socket in angular 6

I am trying to get fetch data from a web socket. I am initializing websocket object as globally.

socket =new WebSocket('ws://xx.xx.xx.xx:xxxx/socket');

on ngOnInit I am opening the connection with :

this.socket.onopen = function(){
    console.log("websocket is open now");
  }

Now I need to send the message using a function which I am triggering from UI and the reply from websocket should store the message in a global variable.

sampleFunction(val) {
    this.socket.send(val);
    this.socket.onmessage=function(event){
      console.log("got message");
      this.dummy=event.data;
    }.bind(this)
  }

So on page load it is getting connected, but when I trigger the function the message is not going and thus I am not getting any response back

Upvotes: 2

Views: 3800

Answers (3)

Manouchehr Rasouli
Manouchehr Rasouli

Reputation: 550

actually in AngularCli applications you can define a service like this and start to connecting into Web socket server

 // websocket.servoce.ts
 import { Injectable } from "@angular/core";
 import { webSocket } from "rxjs/webSocket";


 @Injectable()
 export class WebsocketService {

   // ha ha look at the host address
   private subject = webSocket("ws://xxx.xxx.xxx.xxx:xxxx ;)/ws/");
   // use pipe to push data into components
   constructor() {
     console.log("websocket service initialization");
   }

   subscribe() {
     this.subject.subscribe(
       msg => {
         console.log(msg);
         // use angular data pipe to push data into components that is subscribed on pipe
       },
       err => {
         console.log(err);
       }
      )
   }

 }

take care thanks for using this service

Upvotes: 1

Igor Benić
Igor Benić

Reputation: 73

I believe RxJs sockets expect the payload to be a valid json, are you sending a string or?

Upvotes: 0

Igor Benić
Igor Benić

Reputation: 73

I'm using rxjs that comes with Angular and its webSocket method.

import {webSocket} from 'rxjs/webSocket';
socket = webSocket(`${environment.serviceWebSockets}/api`);
constructor(){
    // now you can subscribe to messages wherever in your code
    this.socket.subscribe(message => {
        console.log(message); // or just use it directly
    }, error => {
        console.error(error); // handle errors
    });
}

to send data over this webSocket:

socket.next(JSON.stringify({some:"data"}));

for connecting use:

socket.subscribe();

for disconnecting:

socket.complete();

more info on https://rxjs-dev.firebaseapp.com/api/webSocket/webSocket

Upvotes: 1

Related Questions