Angular 在父组件中完成服务之前执行的子组件的ngOninit

Angular 在父组件中完成服务之前执行的子组件的ngOninit,angular,angular-routing,Angular,Angular Routing,我有两个组件panelComponent(父组件)和dashboardComponent(子组件)。 panelComponent在其ngOninit中订阅了服务,其返回值在childcomponent ngOninit中使用 问题是,在初始运行我的childs ngonit时,在Parents服务返回值之前执行,我在child组件中得到一个null结果。 如何解决这个问题 panelComponent.ts:- ngOnInit() { this.panelService.ge

我有两个组件panelComponent(父组件)和dashboardComponent(子组件)。 panelComponent在其ngOninit中订阅了服务,其返回值在childcomponent ngOninit中使用

问题是,在初始运行我的childs ngonit时,在Parents服务返回值之前执行,我在child组件中得到一个null结果。 如何解决这个问题

panelComponent.ts:-

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

}
    ngOnInit() {

    console.log(this.panelService.userDetails)

}
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() {
    this.panelService.getUserProfile().subscribe(
        res => {
            this.panelService.userDetails = res;
            this.router.navigate(['panel/dashboard'])
        },
        err => {
            console.log(err);
        },
    ); 

}
    ngOnInit() {

    console.log(this.panelService.userDetails)

}
在初始运行my childs Ngonit时,在Parents服务返回值之前执行

这是因为异步调用。更多关于这张支票的信息,请点击这里

在您的情况下,它应该可以正常工作,最好在将服务重定向到子组件之前检查您从服务获得的响应

panelComponent.ts

我希望这有帮助……)

在初始运行my childs Ngonit时,在Parents服务返回值之前执行

这是因为异步调用。更多关于这张支票的信息,请点击这里

在您的情况下,它应该可以正常工作,最好在将服务重定向到子组件之前检查您从服务获得的响应

panelComponent.ts


我希望这有帮助……)

最简单的方法是使用*ngIf。请参阅BecaUse Ngonin当组件在应用程序中时发生

我创建了一个虚拟服务:

export class DataService {
  data:any;
  getData()
  {
    return of("Angular").pipe(
      delay(500),
      tap(res=>this.data=res)
    )
  }
}
我使用管道(tap)为服务的属性“数据”赋予价值,所以我不需要做任何事情,也不需要订阅任何组件

在app.component中,我有:

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


最简单的方法是使用*ngIf。请参阅BecaUse Ngonin当组件在应用程序中时发生

我创建了一个虚拟服务:

export class DataService {
  data:any;
  getData()
  {
    return of("Angular").pipe(
      delay(500),
      tap(res=>this.data=res)
    )
  }
}
我使用管道(tap)为服务的属性“数据”赋予价值,所以我不需要做任何事情,也不需要订阅任何组件

在app.component中,我有:

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