我正在尝试使用外部JavaScript Web套接字库连接和控制设备。目前我可以从我的角度服务中做到这一点。我无法将连接对象传递给组件。如何在服务客户端对象更新时获得组件更新。任何人都可以帮助我
组件代码
function ViewModel() {
var self = this;
self.exampleData = ko.observableArray([]);
...
self.download = function(data) {
// data => will contain a single object from exampleData array above
$.post(...);
}
}
以下是我的connectService代码
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']);
}
}
}
答案 0 :(得分:0)
我找到了解决问题的方法。我正在分享这个答案,因为这可能会帮助使用Web套接字的人连接到外部设备。我用间隔观察过observable。
let stream$ = new Observable(observer => {
let interval = setInterval(() =>{
observer.next(client.transport.state);
observer.complete();
},1000);
return() =>{
clearInterval(interval);
}
});
return stream$;
然后我只是订阅了该方法并获取了连接细节。
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();
}