【发布时间】:2020-12-10 07:27:17
【问题描述】:
我有以下ChatPanelComponent,其中我创建了getSocket 方法来获取套接字并在连接套接字时调用onopen EventListener。
import { AfterViewInit, Component, ElementRef, OnDestroy, OnInit, QueryList, ViewChild, ViewChildren, ViewEncapsulation } from '@angular/core';
import { NgForm } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { FuseSidebarService } from '@fuse/components/sidebar/sidebar.service';
import { FusePerfectScrollbarDirective } from '@fuse/directives/fuse-perfect-scrollbar/fuse-perfect-scrollbar.directive';
import { ChatPanelService } from 'app/layout/components/chat-panel/chat-panel.service';
import { WebsocketService, UserService } from 'app/core/services';
@Component({
selector : 'chat-panel',
templateUrl : './chat-panel.component.html',
styleUrls : ['./chat-panel.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class ChatPanelComponent implements OnInit, AfterViewInit, OnDestroy
{
contacts: any[];
chat: any;
selectedContact: any;
ws: any;
ws_url: any;
user_id: any;
constructor(
private _chatPanelService: ChatPanelService,
private _user: UserService,
private _WebSocket: WebsocketService,
)
ngOnInit(): void
{
this.ws_url = 'http://localhost:8000/thread/';
this.user_id = this._user.getUser().id;
this.getSocket(this.user_id);
}
getSocket(id: any) {
this.ws = this._WebSocket.connect(this.ws_url+id+'/');
this.ws.onopen = function(e){
console.log("WEBSOCKET OPEN", e);
}
this.ws.onmessage = function(e) {
this.showMessage(e);
}
}
showMessage(msg: any){
console.log("MESSAGE", msg);
}
}
我想在onmessage 事件发生时调用showMessage(msg: any) 方法,并将事件数据传递给showMessage() 方法。但是当调用该方法时,会出现以下错误:
ERROR TypeError: this.showMessage is not a function
at WebSocket.ws.onmessage [as __zone_symbol__ON_PROPERTYmessage]
我想不出任何其他方法来调用该方法。我需要这方面的帮助。 提前致谢!
【问题讨论】:
标签: javascript angular websocket