Reputation: 2036
I have two component with parent and child relationship. Parent component's ngOnInit method checks if the user is logged in or not, if it's not logged in it navigates to the login page.
class ParentComponent implements OnInit{
ngOnInit(){
if(!authService.loggedIn){
//navigate to login screen code
return;
}
}
}
class ChildComponent implements OnInit{
ngOnInit(){
/** POINT TO BE NOTED **/
// this function is also called even if ngOnInit
// of parent navigates to different component and returns.
// do some stuff with userService.token
// but because token isn't available the calls fail
}
}
How do I block this cascading OnInit calls if parent component wants to navigate to other component?
Upvotes: 1
Views: 354
Reputation: 691735
IMO, you should not check if the user is logged in and navigate away from a component. You should instead use a guard to do that.
But, to answer your question, you could just use
<child *ngIf="isLoggedIn()"></child>
That would prevent the child component to be created if the user is not logged in.
Upvotes: 5