Utilizing the github API in my angular 2 application, I encounter an issue where the view renders before ngOnInit has finished loading data. This leads to a
Cannot read property of undefined
error. The relevant portion of my code is as follows:
ngOnInit() {
Observable.forkJoin(
this._githubService.getUser('kaxi1993'),
this._githubService.getFollowers('kaxi1993')
)
.subscribe(res => {
this.user = res[0];
this.followers = res[1];
},
null,
() => {
this.isLoading = false;
});
}
If I structure my HTML like this:
<div *ngIf="user && user.avatar_url">
<img class="media-object avatar" [src]="user.avatar_url" alt="...">
</div>
everything works smoothly. However, if I exclude the *ngIf
directive as shown below:
<img class="media-object avatar" [src]="user.avatar_url" alt="...">
I encounter the error
Cannot read property 'avatar_url' of undefined
. It's worth noting that while getFollowers
behaves correctly, rearranging the order of getUsers
and getFollowers
within the forkJoin
method results in the need for *ngIf
on getFollowers
. Is there a solution to this without adding extra *ngIf
directives? Any assistance would be greatly appreciated. Thank you.