I am trying to connect and control a device with an external JavaScript web-socket library. Currently i am able to do this from my angular service. i am not able to pass the connection object to the component. how can i get update in component when the service client object is updated.Can any one help me please
Component code
doConnect(data){
this.submitted = true;
this.ipaddress = data.ipaddress;
this.portnumber = data.portnumber;
this.data = JSON.stringify(data);
console.log(this.data);
if(this.ipaddress===null && this.portnumber===null){
console.log('Null');
}else{
localStorage.setItem("ipaddress", this.ipaddress);
localStorage.setItem("portnumber", this.portnumber);
//calling the get connect from component
this.connectService.getConnect(this.ipaddress,this.portnumber);
if(localStorage.getItem("clientStatus")=='connected'){
this._router.navigate(['Master']);
}else{
this._router.navigate(['Home']);
}
}
}
Below is my connectService code
getConnect(ipaddress,portnumber){
console.log('coming');
var t = ipaddress;
var p = portnumber;
console.log(t,p);
client = new linear.client({transports: [
{type: 'websocket',
host: t, port: p}
]});
client.connect();
this.getStatusFromMcx();
var osbervable = Rx.Observable.create (function (obs) {
// Handle messages
client.transport.onopen = obs.onOpen.bind(obs);
client.onnotify = obs.onNext.bind(obs);
client.onerror = obs.onError.bind(obs);
client.transport.onclose = obs.onCompleted.bind(obs);
// Return way to unsubscribe
return client.ondisconnect.bind(client);
});
I found a solution for my problem. i am sharing this answer because this may help someone who use web socket to connect to external devices. I have used observable with a interval.
let stream$ = new Observable(observer => {
let interval = setInterval(() =>{
observer.next(client.transport.state);
observer.complete();
},1000);
return() =>{
clearInterval(interval);
}
});
return stream$;
then i just subscribed to that method and getting connection details.
this.subscription = this.AppService.getConnect(this.ipaddress,this.portnumber)
.retry(1)
.subscribe(
value => {
console.log("value+++++",value);
spinner.stop()
if(value=="disconnected" || value=="connecting"){
localStorage.setItem("clientStatus", "disconnected");
spinner.spin(target);
}else{
localStorage.setItem("clientStatus", "connected");
this._router.navigate(['dashboard']);
}
ngOnDestroy() {
// prevent memory leak when component is destroyed
this.subscription.unsubscribe();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.