I'm currently creating an application in angular. The module I am working on gives you ability to join or create a room.
The initial ui of the room module: https://gyazo.com/81afe2b5f7119326d00b518fc4e0979f
upon clicking on "join room" button we go to the join ui: https://gyazo.com/0728a182b27a143fcefd9d71d0c33c44
once I click on the Join button i get an error of:
ERROR DOMException: An attempt was made to use an object that is not, or is no longer, usable
However, once i click the join button for the second time I am able to connect to the websocket server and get no issues
I believe it has something to do with the use of *ngIf
and the dom not loading properly
the main code for the HTML is :
<button *ngIf="isEnterRoomShown" id="createRoomBtn" mat-raised-button (click)="createRoom()">Create Room</button>
<button *ngIf="isEnterRoomShown" id="joinSessionBtn" mat-raised-button (click)="joinRoom()">Join room</button>
<div [hidden]="isEnterRoomShown">
<button id="join" mat-raised-button (click)="join()">Join</button>
</div>
and the component:
createRoom() {
const name = this.nameInput.nativeElement.value;
this.websocket = this.wsService.initWebsocket();
const wsData = {
message: "create-room",
name,
};
this.rService.username = name;
if (this.websocket.readyState === 0) { }
this.waitForSocketConnection(this.websocket, () => {
this.websocket.send(JSON.stringify(wsData));
});
}
joinRoom() {
this.isEnterRoomShown = !this.isEnterRoomShown;
}
join() {
if (!this.websocket) {
this.websocket = this.wsService.initWebsocket();
}
const name = this.nameInput.nativeElement.value;
this.rService.username = name;
if (this.websocket) {
this.websocket.send(
JSON.stringify({
message: "join-room",
name,
id: this.roomId.nativeElement.value,
})
);
}
this.outRoom = false;
this.sessionId = this.roomId.nativeElement.value;
}
I am still pretty new to stackoverflow and angular development, please let me know if you need extra clarification on anything. I have tried to search for similar questions on stackoverflow and have found no answers.
CodePudding user response:
It seems like your code
this.outRoom = false;
this.sessionId = this.roomId.nativeElement.value;
is executed even if your "websocket.send" command is not ended because it's asynchonuous. I don't know how to do this, but you should add something like this :
if (this.websocket) {
this.websocket.send(
JSON.stringify({
message: "join-room",
name,
id: this.roomId.nativeElement.value,
})
).then(() => {
this.outRoom = false;
this.sessionId = this.roomId.nativeElement.value;
});
}
CodePudding user response:
When you use ngIf it creates and destorys HTML DOM Elements. So in this case instead of using ngIf, use hidden directive
[hidden]="!isEnterRoomShown"
This should prevent the node from getting destoryed.