Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 view renders before data loads in ngOnInit [duplicate]

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.

like image 323
kaxi1993 Avatar asked Jun 01 '16 09:06

kaxi1993


1 Answers

You can use the safe-navigation (Elvis) operator to avoid the error like

 <div *ngIf="user?.avatar_url">
   <img class="media-object avatar" [src]="user.avatar_url" alt="...">
 </div>

or

<img class="media-object avatar" [src]="user?.avatar_url" alt="...">
like image 198
Günter Zöchbauer Avatar answered Oct 22 '22 18:10

Günter Zöchbauer