【问题标题】:How to call a method of component inside a function of an event in Angular?如何在Angular中的事件函数内调用组件的方法?
【发布时间】: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


    【解决方案1】:

    您是否尝试过使用箭头功能?它保留了上下文。

    this.ws.onmessage = (e) => { this.showMessage(e); }

    【讨论】:

    • 谢谢你!这对我有用。该消息现在正在控制台上打印。
    【解决方案2】:

    因为事件回调是在 Angular 的上下文之外执行的,所以this 指的是回调事件的上下文而不是 Angular 组件。所以this 不再引用组件的上下文。

    您可以将this 的值保存在任何其他局部变量中并使用它:

    getSocket(id: any) {
           this.ws = this._WebSocket.connect(this.ws_url+id+'/');
     
           this.ws.onopen = function(e){
               console.log("WEBSOCKET OPEN", e);
           }
    
           const self = this; // <- store this value in a local variable
    
           this.ws.onmessage = function(e) {
               self.showMessage(e); //<- use that local variable containing value of component's context
           }
    }
    

    有关它的更多详细信息,请参阅此答案: https://stackoverflow.com/a/20279485/9722122

    【讨论】:

    • 谢谢你 Mustahsan,你的方法对我有用。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2019-02-24
    • 2015-01-10
    • 2020-02-15
    • 1970-01-01
    • 2018-10-28
    • 2019-04-03
    相关资源
    最近更新 更多