ngOninit of child component executing before completing service in parent component

房东的猫 提交于 2019-12-11 15:18:51

问题


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)

}

回答1:


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.. :)




回答2:


The most simple way is using a *ngIf. see stackblitz becaouse ngOnInit happens when is in the application the component

I create a dummy service:

export class DataService {
  data:any;
  getData()
  {
    return of("Angular").pipe(
      delay(500),
      tap(res=>this.data=res)
    )
  }
}

I use pipe(tap) to give value to the propertie "data" of the service, So I needn't do anything also subscribe in any component

In app.component, I has:

ngOnInit()
  {
    this.dataService.getData().subscribe(()=>{});
  }

and

<hello name="{{ name1 }}"></hello>
<hello *ngIf="dataService.data" name="{{ name2 }}"></hello>

In console you see:

name1 undefined
name2 Angular


来源:https://stackoverflow.com/questions/56488381/ngoninit-of-child-component-executing-before-completing-service-in-parent-compon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!