In ngAfterViewInit()
, I'm calling an async method (tried with and without await
) to initialize a table of meetings:
public async getMeetings() {
this.pendingOperation = false;
try {
var { meetingsUrl, bearerToken } = await this.getMeetingsUrl();
var authAndJsonContentHeaderOption = {
headers: {
"Authorization": `Bearer ${bearerToken}`,
"Content-Type": "application/json"
}
};
var httpResult = await this.http.get<any>(meetingsUrl, authAndJsonContentHeaderOption).toPromise();
this.meetings = new Array();
httpResult._embedded.myOnlineMeeting.forEach(element => {
this.meetings.push(element);
});
this.pagedMeetings = this.meetings.slice(0, this.pageSize);
setTimeout(() => {
this.observablePagedMeetings.next(this.pagedMeetings);
}, 100);
}
catch (ex) {
this.errors = `Error: ${ex.message}`;
console.log(`Error: ${ex.message}`);
}
this.pendingOperation = false;
}
As visible in the code above, the retrieved list of meetings is sent to a Subject
so that the view can display it in a paginated material table.
ngAfterViewInit()
is rather simple:
ngAfterViewInit() {
this.filteredUsers.subscribe((filteredUsers) => {
this.displayedUsers = filteredUsers;
});
this.matAutocomplete._keyManager.change.subscribe((index) => {
if (index >= 0) {
this.selectedUser = index;
}
});
this.getMeetings();
}
HTML is:
<table mat-table *ngIf="pagedMeetings" [dataSource]="observablePagedMeetings" style="width: 100%">
<!-- table markup -->
</table>
The problem is that this getMeetings()
is called multiple times instead of once.
So far I've tried:
- using setTimeout to postpone this call
- specifying ChangeDetectionStrategy.OnPush on this component (as suggested here) to break out of a possible change-detection cycle.
Edit:
- Indeed,
ngAfterViewInit()
itself is called multiple times