我目前正在創建一個有角度的應用程式。我正在開發的模塊使您能夠加入或創建房間。
房間模塊的初始ui: https ://gyazo.com/81afe2b5f7119326d00b518fc4e0979f
單擊“加入房間”按鈕后,我們轉到加入用戶界面: https ://gyazo.com/0728a182b27a143fcefd9d71d0c33c44
一旦我單擊加入按鈕,我會收到以下錯誤:
錯誤 DOMException:嘗試使用不可用或不再可用的物件
但是,一旦我第二次單擊加入按鈕,我就可以連接到 websocket 服務器并且沒有問題
我相信這與使用*ngIf和 dom 沒有正確加載有關 HTML 的主要代碼是:
<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>
和組件:
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;
}
我對stackoverflow和角度開發還是很陌生,如果您需要對任何事情進行額外說明,請告訴我。我試圖在 stackoverflow 上搜索類似的問題,但沒有找到答案。
uj5u.com熱心網友回復:
當您使用 ngIf 時,它會創建和銷毀 HTML DOM 元素。所以在這種情況下,不要使用 ngIf,而是使用隱藏指令
[hidden]="!isEnterRoomShown"
這應該可以防止節點被破壞。
uj5u.com熱心網友回復:
好像你的代碼
this.outRoom = false;
this.sessionId = this.roomId.nativeElement.value;
即使您的“websocket.send”命令沒有結束,也會執行,因為它是異步的。我不知道該怎么做,但你應該添加這樣的東西:
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;
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/459035.html
標籤:javascript 有角度的 dom 前端
上一篇:如何在php中正確傳遞頁面ID
下一篇:將資料從Api附加到Dom
