[英]How do i sync a web-socket object from my service to the component -angular 2
I am trying to connect and control a device with an external JavaScript web-socket library. 我正在尝试使用外部JavaScript网络套接字库连接和控制设备。 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 下面是我的connectService代码
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.
我分享此答案,因为这可能会帮助使用Web套接字的人连接到外部设备。 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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.