child 组件的 ngOninit 在完成 parent 组件中的服务之前执行

ngOninit of child component executing before completing service in parent component

我有两个组件 panelComponent(parent) 和 dashboardComponent(child)。 panelComponent 在其 ngOninit 中订阅了一项服务,其 return 值在 childcomponent ngOninit.

中使用

问题是,在初始 运行 我的 childs ngOninit 执行之前 Parents 服务 returns 一个值,我在 [=28 中得到一个空结果=] 组件。 如何解决这个问题?

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)

}

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

这是因为异步调用。有关此的更多信息,请在此处检查一次 .

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

panelComponent.ts

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

希望对您有所帮助..:)

最简单的方法是使用 *ngIf。看到 stackblitz 因为 ngOnInit 发生在应用程序中组件

我创建了一个虚拟服务:

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

我使用 pipe(tap) 为服务的属性 "data" 赋值,所以我不需要做任何事情也订阅任何组件

在app.component中,我有:

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

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

在控制台中您看到:

name1 undefined
name2 Angular