簡體   English   中英

Angular - 在 eventlistener 函數中調用服務函數返回未定義的錯誤

[英]Angular - calling service function inside eventlistener function returns undefined error

免責聲明 -如果標題含糊不清/問題本身很愚蠢,請道歉。 我對 Angular 和 JavaScript 還很陌生

我在一個服務中有一個函數,我試圖在 JavaScript eventListener 函數中調用它,如下所示:

import { WebSocketService } from '../web-socket.service';

@Component({
 selector: 'app-board',
 templateUrl: './board.component.html',
 styleUrls: ['./board.component.css']
})

export class BoardComponent implements OnInit, OnDestroy {

 constructor(private webSocketService: WebSocketService) { }

 ngOnInit() {
   let cells = document.querySelectorAll('.cell');
   for (let i = 0; i < cells.length; i++) {
       cells[i].addEventListener('click', this.cellClicked);
   }
 }

 cellClicked(clickedCellEvent) {
   console.log(this.webSocketService.printSomething());
 }

}  

當我從前端觸發事件(從而調用“cellClicked”函數)時,出現以下錯誤:

core.js:6014 ERROR TypeError: Cannot read property 'printSomething' of undefined

編輯 1:在下面添加服務定義:

import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class WebSocketService {
      printSomething() {
         return "Called a function inside webSocketService!";
      }
}

您需要bindcellClicked方法來this當前上下文

import { WebSocketService } from '../web-socket.service';

@Component({
 selector: 'app-board',
 templateUrl: './board.component.html',
 styleUrls: ['./board.component.css']
})

export class BoardComponent implements OnInit, OnDestroy {

 constructor(private webSocketService: WebSocketService) { }

 ngOnInit() {
   let cells = document.querySelectorAll('.cell');
   for (let i = 0; i < cells.length; i++) {
       cells[i].addEventListener('click', this.cellClicked.bind(this);
   }
 }

 cellClicked(clickedCellEvent) {
   console.log(this.webSocketService.printSomething());
 }

}  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM