Angular JS重新初始化服务



我有一个角度的js服务,它返回一个节点js WebSocket连接。

.service('WebSocketService', function(){
console.log("Starting Web Socket Service...");
var ws= new WebSocket('wss://127.0.0.1:8443/live');
return ws;
})

我在控制器中使用此服务。我想在连接失败的情况下重新连接到节点服务器。为此,我需要从控制器重新初始化此服务(我知道服务是单例的,所以我正在寻找解决问题的方法(

我该怎么做?

.service('WebSocketService', function(){
var conn;
this.connect = function() {
return new WebSocket('wss://127.0.0.1:8443/live');
};
// if you want to connect in the service directly
conn = this.connect();
})

控制器

webSocketService.connect()

您可以将套接字包装到服务将返回的另一个对象中:

.service('WebSocketService', function(){
console.log("Starting Web Socket Service...");
var ws= new WebSocket('wss://127.0.0.1:8443/live');
return {ws : ws,
restart: restart
};
function restart() {
ws = new WebSocket('wss://127.0.0.1:8443/live');
return ws;
}
})

因此,在您的控制器中,我认为您需要执行以下操作:

.controller('SomeController', ['WebSocketService', '$timeout', function(WebSocketService, $timeout){
this.ws = WebSocketService.ws;
this.ws.onclose = function(){
$timeout(function(){
this.ws = WebSocketService.restart();
}, 4000)
}
}])

我为此使用了重新连接网络套接字 js 库,效果很好!

参考: https://github.com/pladaria/reconnecting-websocket

谢谢
拉吉

最新更新