Edw*_*ard 7 javascript components websocket angular
我开始构建一个应用程序.有很多组件.他们每个人都需要来自1个webSocket的一部分数据.webSocket接收对象的示例:
每个Angular 2组件需要1个来自接收对象的字段.是否可以创建1个服务,它将连接到webSocket,接收数据并在所有组件之间共享?我认为这将是一个很好的解决方案.
现在我正在使用下一个方法:
getConfigCallback() {
this.connectionSockets.telemetry = io(this.config.connections.telemetry);
this.connectionSockets.controlFlow = new WebSocket(this.config.connections.controlFlow.server + ':' + this.config.connections.controlFlow.port);
this.connectionSockets.telemetry.on('telemetry', function(data) {
console.log(data);
});
this.connectionSockets.controlFlow.onopen = function(data) {
console.log('onOpen', data);
};
this.connectionSockets.controlFlow.onmessage = function(data) {
console.log('onMessage', data);
};
}
Run Code Online (Sandbox Code Playgroud)
我在主要组件中接收数据,并希望使用组件的实例在组件之间共享它.但我认为这是一个坏主意,并且存在更好的解决方案.
当你引导应用程序时,你可以通过设置它的提供者来共享你的服务:
bootstrap(AppComponent, [ WebSocketService ]);
Run Code Online (Sandbox Code Playgroud)
这样,您将在整个应用程序中共享相同的服务实例.我的意思是当你注入WebSocketService
服务时,相应的实例将是相同的组件/服务.
为了能够共享收到的数据,我会利用热点可观察性.默认情况下,observable是冷的,因此您需要使用share
运算符.
initializeWebSocket(url) {
this.wsObservable = Observable.create((observer) => {
this.ws = new WebSocket(url);
this.ws.onopen = (e) => {
(...)
};
this.ws.onclose = (e) => {
if (e.wasClean) {
observer.complete();
} else {
observer.error(e);
}
};
this.ws.onerror = (e) => {
observer.error(e);
}
this.ws.onmessage = (e) => {
observer.next(JSON.parse(e.data));
}
return () => {
this.ws.close();
};
}).share();
}
Run Code Online (Sandbox Code Playgroud)
想要从Web套接字接收数据的组件可以通过这种方式使用此可观察对象:
@Component({
(...)
})
export class SomeComponent {
constructor(private service:WebSocketService) {
this.service.wsObservable.subscribe((data) => {
// use data
});
}
}
Run Code Online (Sandbox Code Playgroud)
有关"基于事件的方法"部分的更多详细信息,请参阅此文章:
归档时间: |
|
查看次数: |
3466 次 |
最近记录: |