我正在尝试为套接字创建一个模型类,以便我可以在需要的地方使用该套接字模型。
我正在尝试在其他文件中使用此套接字模型类的实例。
我能够成功地做到这一点。
otherFiles.js
:
import Sockette from '../utilities/otherFiles';
const Sockete = new Sockette(url,Id) // creating the instance and passing the parameter values to that instance class
Sockette.ts
:
import sockette from 'sockette';
export default class Sockette {
public ws : any;
public Id : string;
public pingInterval : any;
public dataReceived : any;
public url : string;
constructor(url: string,Id: string){
this.Id = Id;
this.url = url;
this.ws = new sockette(`${url}?Id=${this.Id}`,{onclose: this.onClose,onerror: this.onError,onopen: this.onOpen,onmessage: this.onMessage});
}
public onClose(events: any) {
console.log('Closed!', events);
}
public onError(events:any) {
console.log('Error!', events);
}
public onOpen(events:any) {
console.log("Id :",this.Id) // gives me error that Id is undefined
console.log('Open!', events);
this.ws.json({action:'GET_STATUS', Id: this.Id});
this.pingInterval = setInterval(function() {
this.ws.json({action:'PING'});
},1000);
}
public onMessage(events:any) {
try {
this.dataReceived = JSON.parse(events.data);
} catch(err) {
console.log('Data received not a JSON');
}
if (this.dataReceived && this.dataReceived.action === 'ORDER_STATUS') {
console.log("dataReceived :",this.dataReceived)
return this.dataReceived.value
}
}
}
但是如果我尝试访问 Sockette 模型内
this.id
中的 this.ws
或 public onOpen()
,它会说它未定义
错误:
类型错误:无法读取未定义的属性“Id”
打开时
28 | 28 }
29 |
30|公共 onOpen(事件:任何){
31 | console.log("Id :",this.Id)
32 | 32 console.log('打开!', events);
尝试使用箭头功能
public onOpen(events:any) => {
console.log("Id :",this.Id)
console.log('Open!', events);
this.ws.json({action:'GET_STATUS', Id: this.Id});
this.pingInterval = setInterval(function(){
this.ws.json({action:'PING'});
},1000);
}
你应该将你的函数绑定到 Sockette 类的 this ,并将这些行添加到构造函数中
this.onError = this.onError.bind(this);
this.onClose = this.onClose.bind(this);
this.onOpen= this.onOpen.bind(this);
this.onMessage= this.onMessage.bind(this);