Jay
Jay

Reputation: 280

Angular 10: How to load user information back on page refresh

I have an angular app that loads user related information (user's favorites, selected items etc) through separate API call when user logs in.

It's a simple GET API call & in login component, I redirect user to dashboard once the call to this API is completed.

The result of this API is used on dashboard page. When user refresh the dashboard page, the object is null. I tried to call the API is app component ng oninit method, but the code accessing object in dashboard component is execute before completing this API.

How can I wait for the API call to complete?

Upvotes: 0

Views: 548

Answers (1)

Tonnio
Tonnio

Reputation: 655

What you need is to ensure that the content is presented only after the request has been successfully completed. You can complete using the *ngIf directive. There're two ways to do that:

Without async pipe.

template:

<ng-container *ngIf="userData">
    <!-- Your dashboard code here -->
</ng-content>

controller:

userData?: any;

...

ngOnInit() {
    this.userDataService.get().subscribe(res => {
        this.userData = res;
    });
}

With async pipe.

template:

<ng-container *ngIf="userData$ | async">
    <!-- Your dashboard code here -->
</ng-content>

controller:

userData$?: Observable<any>;

...

ngOnInit() {
    this.userData$ = this.userDataService.get();
}

Upvotes: 1

Related Questions