Search code examples
angularangular-routing

ngOninit of child component executing before completing service in parent component


I have two component panelComponent(parent) and dashboardComponent(child). The panelComponent has a subscription to a service in its ngOninit and its return value is used inside childcomponent ngOninit.

The Problem is, on initial running my childs ngOninit executing before Parents service returns a value and I am getting a null result in child component. How to solve this issue?

panelComponent.ts:-

    ngOnInit() {
    this.panelService.getUserProfile().subscribe(
        res => {
            this.panelService.userDetails = res;
            this.router.navigate(['panel/dashboard'])
        },
        err => {
            console.log(err);
        },
    ); 

}

panelService.ts:-

export class PanelService {
userDetails;
constructor(private http: HttpClient) {
}
getUserProfile() {
    const httpOptions = {
        headers: new HttpHeaders({
            'Authorization': `Bearer ${localStorage.getItem('token')}`
        })
    };
    return this.http.get('/api/UserProfile/UserProfile', httpOptions);
}

dashboardComponent.ts:-

    ngOnInit() {

    console.log(this.panelService.userDetails)

}

Solution

  • on initial running my childs ngOninit executing before Parents service returns a value

    This is because of Async calls. for more about this check here once Properly use Async calls with Angular 5.

    In your case it should work fine, it's better to check the response your getting from the service before redirecting it to the child component.

    panelComponent.ts

      ngOnInit() {
        this.panelService.getUserProfile().subscribe(
            res => {
              if(res) {
                 this.panelService.userDetails = res;
                 this.router.navigate(['panel/dashboard'])
              }
            },
            err => {
                console.log(err);
         }); 
    }
    

    I hope this helps.. :)