2017-09-24 41 views
2

每次訪問routerLink時我都需要調用ngOnInIt方法,因爲我在當前訪問的鏈接中使用ID來綁定和檢索數據庫中的數據,並且如果未調用該方法我失去了這些數據。訪問路由器鏈接時重新載入組件

這裏是我的init()方法的一個例子(抱歉不知道如何使用此代碼段)

ngOnInit() { 
    this.authService.getAuth().subscribe(auth=> { 
     if(auth) { 
      this.loggedInUser = auth.email; 
     } else { 
     } 
    }); 

    this.teamService.getTeams().subscribe(teams => { 
     this.teams = teams; 
     console.log(this.teams); 
     for(var i = 0; i < this.teams.length; i++) { 
      if(this.teams[i].createdBy == this.loggedInUser) { 
       this.myTeams.push(this.teams[i]); 
      } 
     }  
    }); 

    console.log(this.myTeams); 

    this.id = this.route.snapshot.params['id']; 

    //Get Team 
    this.scrimService.getScrim(this.id).subscribe(scrim => { 
     this.scrim = scrim; 
    }); 

} 

,這裏是路由器的鏈路我使用去這個組件

<a *ngIf="recordOwner" [routerLink]="['/edit-scrim/'+id]" class="btn btn secondary">Edit</a> 

我一些答案像我類似的問題,我可以使用activatedRoute.paramssubscribe的數據在構造函數中,這樣從ngOnInit方法都被稱爲在構造函數中閱讀,但我不知道這意味着什麼,以及如何AC complish在我的情況:/

編輯

id: string; 
loggedInUser: string; 

scrim: Scrim = { 
name: '', 
game: '', 
time: '', 
level: '', 
description: '', 
region: '', 
platform: '', 
acceptedBy: '', 
acceptedDate: '', 
acceptedStatus: '', 
createdBy: '', 
createdDate: '', 
team: '' 

} 

teams: Team[]; 
myTeams: Team[] = []; 
currentDate: string; 
currentTime: string; 

我有從火力數據庫中獲取「團隊」和返回模型的陣列的服務。我正在使用當前登錄用戶的電子郵件地址來查找僅由當前用戶創建的團隊。一旦我在數組myTeams中擁有這些團隊,我然後嘗試用myTeams列表中的團隊名稱填充選擇的html標記以供用戶選擇。我第一次進入這個編輯頁面時,選擇標籤中的團隊填充得很好,但如果我移動到另一個頁面並使用RouterLink返回到此編輯頁面頁面,則選擇列表不會填充,因爲它不會填充「再次調用ngoninit方法,所以如果我刷新我的網頁,團隊再次填充,我猜測是因爲ngoninit被再次調用。

回答

0

您需要的activatedRoute注入到你的構造是這樣,

constructor(private activatedRoute: ActivatedRoute) { 
this.activatedRoute.params.subscribe(
params =>{ 
    this.id = params['id']; 
    this.scrimService.getScrim(this.id).subscribe(scrim => { 
     this.scrim = scrim; 
    }); 

} 
} 
+0

但這不會再次致電或init方法重新加載組件:/ –

+0

您需要在API調用的代碼添加到另一種方法和在'this.id = parmas ['id'];' –

+0

後調用該方法我更新了我的答案,以包含API調用,看看它是否可以工作 –

相關問題