简体   繁体   English

如何在 Angular 的事件的 function 中调用组件的方法?

[英]How to call a method of component inside a function of an event in Angular?

I have the following ChatPanelComponent in which I have a created getSocket method to get a socket and called the onopen EventListener when the socket is connected.我有以下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);
  }
}

I want to call the showMessage(msg: any) method when the onmessage event occurs and and pass the event data to the showMessage() method.我想在onmessage事件发生时调用showMessage(msg: any)方法,并将事件数据传递给showMessage()方法。 But when the method is called it gives the following error:但是当调用该方法时,会出现以下错误:

ERROR TypeError: this.showMessage is not a function
    at WebSocket.ws.onmessage [as __zone_symbol__ON_PROPERTYmessage]

I can't think of any other ways to call the method.我想不出任何其他方法来调用该方法。 I need help in this.我需要这方面的帮助。 Thanks in Advance!提前致谢!

Because event callbacks are executed outside Angular's context, this refers to callback event's context rather than angular components.因为事件回调是在 Angular 的上下文之外执行的, this指的是回调事件的上下文,而不是 angular 组件。 so this does not refers to component's context anymore.所以this不再指代组件的上下文。

you can save value of this inside any other local variable and use that:您可以将它的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
       }
}

For more detail about it please refer to this answer: https://stackoverflow.com/a/20279485/9722122有关它的更多详细信息,请参阅此答案: https://stackoverflow.com/a/20279485/9722122

Have you tried using arrow function?您是否尝试过使用箭头 function? It preserves the context.它保留了上下文。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM