ngOnInitで非同期取得 → 値の取得後にコールバックやSubjectでngAfterViewInitへイベント通知する方法
ngOnInitで取得したデータをngAfterViewInitなどで確実に使いたいときなど
import { Component, OnInit, AfterViewInit } from '@angular/core';
import { Subject } from 'rxjs';
@Component({
selector: 'app-sample',
template: `...`
})
export class SampleComponent implements OnInit, AfterViewInit {
data: any;
dataLoaded$ = new Subject<any>();
ngOnInit() {
this.getDataAsync().then(result => {
this.data = result;
this.dataLoaded$.next(result); // データ取得完了を通知
});
}
async getDataAsync() {
// 非同期でデータ取得
return await fetchDataFromServer();
}
ngAfterViewInit() {
this.dataLoaded$.subscribe(data => {
// この中なら確実にdataが取得済み
console.log('afterViewInitでデータ利用:', data);
});
}
}