从 MenuItem 命令回调访问父组件

Access parent component from MenuItem command callback

我在 Angular 5 应用程序中使用 PrimeNG 5.2

我正在尝试在用户单击菜单项时显示产品列表。

为此,我有一个 PanelMenu,其中第一级项目包含产品的主要类别,第二级包含子类别。在第二层中,每个子类别都有一个关联的 click event,我需要在其中放置一些逻辑(按类别获取产品,显示 table 等)。

这是我目前的工作代码:

(...)
// Populate second level items with subcategories
categories.forEach(cat =>
{
    if(cat['parent'] == category['id']) // 'category' is the first level category
    {
        subcats.push({
            label: cat['description'],
            id: cat['id'],
            command: this.subCatClick
        });
    }
});
items.push({label: category['description'], items: subcats});  // Items of the menu
subCatClick(event)
{
    //this.logger.log(`clicked on cat ${event.item.label}`, false);
    //this.getProductByCategoryId(event.item.id);

    // 'this' refers to the item here !
    console.log(this);
}

如评论所述,this 指的是 MenuItem(此处为子类别),因此不包含对我要调用的功能/服务的任何引用(在上面的例子)。

这些功能/服务是包含 PanelMenucomponent 的成员。如何从 click event 访问它们?

感谢您的帮助。

重写传递函数引用的行:

command: this.subCatClick

到箭头函数语法,它将 'this' 绑定到被调用者的 'this':

command: (event) => this.subCatClick(event)

或者你可以使用 .bind 关键字 javascript:

command: this.subCatClick.bind(this)