2017-10-16 17 views
0

menuというモジュールの中にMenuComponentがあり、このコンポーネントのgetMenu(path:string)メソッドを別のモジュールのAppComponentに呼び出したいとします。別のコンポーネントが別のモジュールにある場合、コンポーネントのメソッドを別のコンポーネントから呼び出すにはどうすればいいですか?

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

} 

} 

答えて

1

インポートモジュール、およびメソッドを呼び出す - あなたのケースで、それはインスタンスメソッドなので、2番目の例では、動作するはずです...静的およびインスタンスのバージョンは以下の通り:

これが私のMenuComponentです。

import { MenuComponent } from './menu'; 

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

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

メニューサービスを挿入する必要があります。モジュールをインポートして、同じ方法でそれらのモジュールの1つを構築することができます。

これを行う方法については、Angular component interaction docsを参照してください。 2つのコンポーネント間で相互作用するための複数のきちんとしたパターンがあります。

関連する問題