I use github API to load user and his followers data in my angular 2 app, but view renders before ngOnInit finishes load data and because of this I receive:
Cannot read property of undefined
error. My code fragment looks like this:
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 write html code like this:
<div *ngIf="user && user.avatar_url">
<img class="media-object avatar" [src]="user.avatar_url" alt="...">
</div>
works fine, but returns error Cannot read property 'avatar_url' of undefined
when write html code without *ngIf
like this:
<img class="media-object avatar" [src]="user.avatar_url" alt="...">
also note: getFollowers
works fine, but if I move
getFollowers
before getUsers
in forkJoin
method then getUsers
works fine and getFollowers
need *ngIf
to avoid error.
Is it possible to write without extra *ngIf code? any help guys, Thanks a lot.