2017-05-08 75 views
0

我有兩個組件與父母和孩子的關係。父組件的ngOnInit方法檢查用戶是否登錄,如果沒有登錄,則導航到登錄頁面。如何避免級聯ngOnInit?

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

如果父組件想要導航到其他組件,如何阻止此級聯OnInit調用?

回答

3

IMO,你不應該檢查用戶是否登錄並離開組件。您應該改用guard來做到這一點。

但是,要回答你的問題,你可以只使用

<child *ngIf="isLoggedIn()"></child> 

這將防止子組件被創建,如果用戶沒有登錄。

+0

我知道網址防護,但我認爲從父母的ngOnInit返回會工作,但它不會那樣工作。 URL防護無疑是正確的做法,它發生在組件初始化之前的導航過程中。非常感謝,夥計。 – mdanishs