简体   繁体   中英

Angular - calling service function inside eventlistener function returns undefined error

Disclaimer- Apologies if the title is ambiguous/the question itself is silly. I'm fairly new to Angular and JavaScript

I have a function in a service which I'm trying to call inside a JavaScript eventListener function, like 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);
   }
 }

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

}  

When I trigger the event from front-end(and thereby calling the 'cellClicked' function), I'm getting the following error:

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

Edit 1: Adding Service Definition below:

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!";
      }
}

You need to bind the cellClicked method to this current context

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());
 }

}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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