在父组件中完成服务之前执行的子组件的 ngOninit [英] ngOninit of child component executing before completing service in parent component

查看:16
本文介绍了在父组件中完成服务之前执行的子组件的 ngOninit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个组件 panelComponent(parent) 和dashboardComponent(child).panelComponent 在其 ngOninit 中订阅了一项服务,其返回值在子组件 ngOninit 中使用.

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.

问题是,在Parents服务返回一个值之前,我的孩子的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:-

panelComponent.ts:-

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

}

panelService.ts:-

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

dashboardComponent.ts:-

    ngOnInit() {

    console.log(this.panelService.userDetails)

}

推荐答案

在父母服务返回值之前执行我的孩子的 ngOninit 的初始运行

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

这是因为异步调用.有关此检查的更多信息,请在此处正确使用 Angular 5 的异步调用.

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

这篇关于在父组件中完成服务之前执行的子组件的 ngOninit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆