gpt4 book ai didi

javascript - Angular - 在事件监听器函数内调用服务函数返回未定义的错误

转载 作者:行者123 更新时间:2023-11-28 16:53:42 25 4
gpt4 key购买 nike

免责声明 - 如果标题不明确/问题本身很愚蠢,我们深表歉意。我对 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!";
}
}

最佳答案

您需要将cellClicked方法绑定(bind)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());
}

}

关于javascript - Angular - 在事件监听器函数内调用服务函数返回未定义的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59600897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com