我的Web套接字连接代码:
public connect(): Subject<MessageEvent> {
if (!this.subject) {
this.subject = this.create(this.url);
}
this.ws.onerror = () => {
this.close();
let refresh = setInterval(() => {
this.subject = null;
this.connect();
this.ws.onopen = () => {
clearInterval(refresh)
}
}, 5000);
}
return this.subject;
}
private create(url: string){
this.ws = new WebSocket(url);
const observable = Observable.create((obs: Subject<MessageEvent>) => {
this.ws.onmessage = obs.next.bind(obs);
this.ws.onerror = obs.error.bind(obs);
this.ws.onclose = obs.complete.bind(obs);
this.ws.onclose = function () {
console.log("trying to reconnect");
this.connect();
}
return this.ws.close.bind(this.ws);
});
const observer = {
next: (data: any) => {
if (this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(data));
}
}
};
return Subject.create(observer, observable);
}
如果连接关闭,我想重新连接Web套接字。目前,当我停止Web套接字时,该功能变得很混乱。 BUt不再连接。我看到错误“ this.connect不是一个函数”。如何使用角度递归函数?
答案 0 :(得分:1)
如果您不知道其如何根据执行上下文更改function
引用,请不要在其中使用this
时使用this
关键字来创建回调,使用箭头功能代替
要使其重新连接,请更改此
this.ws.onclose = function () {
console.log("trying to reconnect");
this.connect();
}
对此
this.ws.onclose = () => {
console.log("trying to reconnect");
this.subject = null;
this.connect();
}