2
0

More than 3 years have passed since last update.

[Angular] 子から親のメソッドを実行したらメソッド内のServiceでエラーが発生してハマった

Last updated at Posted at 2020-01-09

[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でしたが、親コンポーネントで閉じているオブジェクトを使用する場合は注意が必要ということです。
子コンポーネントで閉じているオブジェクトは引数で渡してあげましょう。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0