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

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

问题描述

我有两个组件panelComponent(父级)和dashboardComponent(子级). 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.

问题是,在父项服务返回值之前,我的子项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在Parents服务返回值之前执行

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天全站免登陆