1. ホーム
  2. javascript

[解決済み] Angularです。ライフサイクルフックのうち、Componentが利用できる入力データはどれか?

2022-11-14 09:06:53

質問

の配列を受け取るコンポーネントがあります。 image オブジェクトの配列を Input のデータとして使用することができます。

export class ImageGalleryComponent {
  @Input() images: Image[];
  selectedImage: Image;
}

コンポーネントのロード時に selectedImage の最初のオブジェクトに設定されるようにしたいです。 images 配列の最初のオブジェクトに設定されます。私はこれを OnInit のライフサイクルフックをこのようにします。

export class ImageGalleryComponent implements OnInit {
  @Input() images: Image[];
  selectedImage: Image;
  ngOnInit() {
    this.selectedImage = this.images[0];
  }
}

この場合、エラーが発生します。 Cannot read property '0' of undefined というエラーになり、これは images の値はこのステージに設定されていないことを意味します。また OnChanges フックも試しましたが、配列の変化を観察する方法についての情報を得ることができず、行き詰まっています。どうすれば期待通りの結果を得られるのでしょうか?

親コンポーネントはこのような感じです。

@Component({
  selector: 'profile-detail',
  templateUrl: '...',
  styleUrls: [...],
  directives: [ImageGalleryComponent]
})

export class ProfileDetailComponent implements OnInit {
  profile: Profile;
  errorMessage: string;
  images: Image[];
  constructor(private profileService: ProfileService, private   routeParams: RouteParams){}

  ngOnInit() {
    this.getProfile();
  }

  getProfile() {
    let profileId = this.routeParams.get('id');
    this.profileService.getProfile(profileId).subscribe(
    profile => {
     this.profile = profile;
     this.images = profile.images;
     for (var album of profile.albums) {
       this.images = this.images.concat(album.images);
     }
    }, error => this.errorMessage = <any>error
   );
 }
}

親コンポーネントのテンプレートには、この

...
<image-gallery [images]="images"></image-gallery>
...

どのように解決するのですか?

入力プロパティは ngOnInit() が呼び出される前に入力されます。 しかし、これは、子コンポーネントが作成されるときに、入力プロパティをフィードする親プロパティがすでに入力されていると仮定しています。

画像データはサービスから非同期に取り込まれます(したがって、httpリクエストです)。 したがって、入力プロパティは ngOnInit() が呼び出されたとき、input プロパティは入力されません。

問題を解決するには、サーバーからデータが返されたときに、新しい配列をparentプロパティに代入してください。 実装 ngOnChanges() を子の中に入れてください。 ngOnChanges() は、Angularの変更検出が新しい配列の値を子へ伝搬するときに呼び出されます。