gpt4 book ai didi

Angular 在点击回调函数中调用另一个函数(this)

转载 作者:行者123 更新时间:2023-12-02 20:26:28 24 4
gpt4 key购买 nike

我认为这个问题与关键字“this”没有分配给我假设的内容有关。

我正在使用 Angular 5 和 WordCloud 包。 https://github.com/timdream/wordcloud2.js/blob/gh-pages/API.md

有一个点击回调函数,它返回回调中点击的单词的单个字符串。当用户单击该单词时,我需要它调用另一个函数并显示模式。

组件.ts

import { Component, OnInit, Input } from '@angular/core';
const WordCloud = require('wordcloud');

import { MatDialog, MAT_DIALOG_DATA } from '@angular/material';
import { TopWordsModalComponent } from './top-words-modal/top-words-modal.component';

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

export class TopWordsComponent implements OnInit {

@Input() report;
categories: any = null;
filterForm: FormGroup;

constructor(private fb: FormBuilder, public modal: MatDialog) {

}

ngOnInit() {

const all_words = this.report.activity.top_words;

this.generateWordCloud(all_words);

}

generateWordCloud(words) {

WordCloud(document.getElementById('word_cloud'), {

list: words,
click: function (data) {
console.log(this);
this.openModal(data);
},
classes: ['clickable']

});
}

openModal(word) {

this.modal.open(TopWordsModalComponent, {

width: '1020px',
data: { report: this.report, word: word }

});

}


}

但是当它尝试调用 this.openModal() 时我收到以下错误:

core.js:1448 ERROR TypeError: this.openModal is not a function at Object.click (top-words.component.ts:79) at HTMLDivElement.wordcloudclick (wordcloud2.js:440) at ZoneDelegate.invokeTask (zone.js:421) at Object.onInvokeTask (core.js:4740) at ZoneDelegate.invokeTask (zone.js:420) at Zone.runTask (zone.js:188) at ZoneTask.invokeTask [as invoke] (zone.js:496) at invokeTask (zone.js:1517) at HTMLDivElement.globalZoneAwareCallback (zone.js:1543)

console.log 给出了单词 object。

{list: Array(100), fontFamily: "Times, serif", fontWeight: "normal", color: ƒ, minSize: 0, …}

你能看到它是如何引用“对象点击”的吗?我相信“this”属性被分配给回调对象而不是我的组件,所以我无法调用另一个函数。

这里的解决方案是什么?

最佳答案

使用arrow function() => 而不是 function 关键字。带有 function 关键字的方法有自己的 this 上下文,并隐藏对类属性/方法的访问,而与此相反到箭头函数。

如 Mozilla Web 文档中所述:

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

将代码更改为以下内容:

generateWordCloud(words) {
WordCloud(document.getElementById('word_cloud'), {
list: words,
click: (data) => {
console.log(this);
this.openModal(data);
},
classes: ['clickable']
});
}

关于Angular 在点击回调函数中调用另一个函数(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49748923/

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