[Angular] 子コンポーネントから親コンポーネントのメソッドを実行して戻り値を受け取る
からの派生記事です。
やりたかったこと
- 子から親のコンポーネントを受け取りメソッドを実行する
- 親メソッド内でDIしたServiceを呼んでいる
- 戻り値を受け取りたい
ダメな例
parent-compomemt.html
<parent-compomemt>
<child-compomemt [parentFunc]="parentFunc">
</parent-compomemt>
親から子へ渡す
parent-component.ts
constructor (
private hogeService: HogeService,
) {}
async parentFunc() {
return this.hogeService.getHoge();
}
子で受け取る
child-component.ts
@Input() parentFunc: () => Promise<Hoge>;
async callParentFunc() {
const hoge = await this.parentFunc();
}
しかし、実際に実行するとメソッド内のthisがChildComponent
を参照しており
hogeServiceがundefind
となってしまう。
解決策
その1
一番簡単な解決方法。
子コンポーネント内では使用しないがDIしておく。
ただ、一見使用しないDIに見えるので気持ち悪い。
child-component.ts
@Input() parentFunc: () => Promise<Hoge>;
constructor (
private hogeService: HogeService,
) {}
async callParentFunc() {
const hoge = await this.parentFunc();
}
その2
私はこの方法で解決しました。
親のコンテキストを渡して実行する。
親で定義しているメソッドなので親のコンテキストを渡してあげるのが自然だと私は思う。
child-component.ts
@Input() parentFunc: () => Promise<Hoge>;
private _parent: ParentComponent;
constructor (
@Host() parent: ParentComponent,
) {
this._parent = parent;
}
async callParentFunc() {
const hoge = await this.parentFunc.call(this._parent);
}
まとめ
今回はServiceでしたが、親コンポーネントで閉じているオブジェクトを使用する場合は注意が必要ということです。
子コンポーネントで閉じているオブジェクトは引数で渡してあげましょう。