在使用了打字稿/ vue和websockets之后,我注意到一些非常相似的行为,其中一个打字稿变量似乎采用了另一个打字稿变量。我知道这可能会在javascript中发生,但是在打字稿中,我相信这是不可能的,因为能够定义“类”,尽管可以在javascript中进行转置,但是如果创建它,它仍然可以充当独立的对象。 / p>
对我来说,这更多是关于幕后发生的确切情况。
我可以通过简单地更改变量名来确认,这可以正常工作,但没有尝试其他方法来查看会发生什么。
WebsocketRequestService.ts
export class WebSocketRequestService {
...
/**
* @param data Opens a socket for a request style response.
*/
public sendRequest(data: string): void {
const socket: WebSocket = new WebSocket(this.location);
socket.onopen = () => {
socket.send(data);
console.log('sending:' + data);
this.timeoutObj = setTimeout(() => {
socket.close();
console.log('Time out occured.');
}, 3000);
};
socket.onmessage = (event: MessageEvent) => {
clearTimeout(this.timeoutObj);
if (isNull(this.messageListener)) {
return;
}
if (isUndefined(this.messageListener)) {
return;
}
this.messageListener(event.data);
};
socket.onerror = (event: Event) => {
clearTimeout(this.timeoutObj);
if (isNull(this.errorListener)) {
return;
}
if (isUndefined(this.errorListener)) {
return;
}
this.errorListener(event);
};
socket.onclose = (event: CloseEvent) => {
clearTimeout(this.timeoutObj);
if (isNull(this.closeListener)) {
return;
}
if (isUndefined(this.closeListener)) {
return;
}
this.closeListener(event);
};
}
Login.vue
export default Vue.extend ({
components: {
AButton,
},
props: {
},
data() {
return {
userName: '',
password: '',
result: '',
socket: new WebSocketService("localhost:8082/time"),
time: '0',
};
},
methods: {
init(): void {
this.socket.addMessageListener((data: string): void => {
this.time = data;
});
},
sendRequest(): void {
let authData: UserAuthentication = new UserAuthentication(this.userName,this.password);
let requestSocket: WebSocketRequestService = new WebSocketRequestService('localhost:8082/login');
requestSocket.setOnReply((replyData: string) => {
console.log(replyData);
this.result = replyData;
});
const userdata = {
userName: this.userName,
password: this.password,
};
const dataString: string = JSON.stringify(userdata);
requestSocket.sendRequest(dataString);
},
},
mounted() {
this.init();
},
beforeDestroy(){
this.socket.close();
}
});
运行此代码并发出登录请求后,请求完成后,两个套接字都将关闭。
但是,如果我将不同作用域之一中的变量之一重命名为'socket'以外的其他东西,它将按预期运行(哪个套接字关闭,而另一个套接字保持运行)