Search code examples
angularangular7angular-routing

Child route reloading without getting data from parent route


I have a component 'panel' which is having two child routes dashboard and holidays. Both these child routes are getting a data on their ngOnInit from parent component service.

Everything is working fine and dashboard is loading with data if we are going in normal way, but if we are reloading the child route its not getting the parent service data.

How to solve this issue?

Routing module:-

{
    path: 'panel',
    component: PanelComponent,
    canActivate: [AuthGuard],
    children: [

        {
            path: 'dashboard',
            component: DashboardComponent,

        },
        {
            path: 'holidays',
            component: HolidaysComponent
        }
    ]
}

panelComponent.ts:-

export class PanelComponent implements OnInit {

constructor(private panelService: PanelService, route: ActivatedRoute, private router: Router) {

}

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

DashboardComponent.ts:-

export class DashboardComponent {
/** dashboard ctor */

private userDetails = {
    name:""
}
constructor(private panelService: PanelService) {

}
ngOnInit() {
    //console.log(this.panelService.userDetails.profileDetails[0].name);
    this.userDetails.name=this.panelService.userDetails.profileDetails[0].name
}

Solution

  • It's good to share data between the components when these components are getting rendered for single route.

    Everything is working fine

    In this case you are child components will render after the Parent component, but sometimes you need to refresh from the child route then you need to call the service method itself from the child component.

    I think you need refactor your child component something like below

    ngOnInit() {
      if(!this.panelService.userDetails) { 
         this.panelService.getUserProfile().subscribe( res => {
            this.panelService.userDetails = res;
          },
          err => {
            console.log(err);
          }); 
      }
      this.userDetails.name = this.panelService.userDetails.profileDetails[0].name;
    }
    

    Edit

    BehaviorSubject is good approach for your requirement. But but if you are reloading the child route itself, there maybe a chance that you will lose the data in behaviorSubject oject too.

    If you think you need to have the data even child route get refreshed, checking the data from the Child component is better approach.(at least in my opinion).