簡體   English   中英

如果另一個組件位於不同的模塊中,如何從另一個組件調用該組件的方法?

[英]How do I call a component's method from another component if they're in different modules?

我在一個名為menu的模塊內有一個MenuComponent ,我想在另一個模塊中的AppComponent此組件的getMenu(path:string)方法。

這是我的MenuComponent

import { Component, OnInit } from '@angular/core';
import {
TreeComponent,
TreeNode,
} from 'angular-tree-component';
import { MenuService } from '../../menu.service';

@Component({
selector: 'menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.css']
})
export class MenuComponent {

constructor(private menuService: MenuService) { }

nodes:any;

 getMenu(path:string): void {
   this.menuService.getData(path).subscribe(data => {
         // Read the result field from the JSON response.

         let newValue = JSON.stringify(data).replace('{"Node":', '[');
         newValue = newValue.substring(0,newValue.length - 1);
         newValue+="]";
        const menu=JSON.parse(newValue);
         this.nodes = menu;
      });

 }

}

導入模塊,並調用方法-如下所示的靜態版本和實例版本...在您的情況下,它是一個實例方法,因此第二個示例應該可以工作。

import { MenuComponent } from './menu';

// Static
MenuComponent.getMenu('...');

// or Instance
const menu = new MenuCompnent(myMenuService);
menu.getMenu('...');

您需要注入菜單服務。 您可以導入模塊並以相同的方式構造其中之一。

查看Angular組件交互文檔,以了解如何執行此“ Angular Way”。 在兩個組件之間進行交互時,存在多種簡潔的模式。

暫無
暫無

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

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