[英]Angular 6 navbar routerlink reload component
我在導航欄中的下拉菜單中使用了angular 6和routerlink。 我面臨的問題是routerlink不會重新加載網站,因此沒有路由。 當按下下拉菜單中的按鈕時,它最初會正確加載,但是當用戶按下下拉菜單中的另一個按鈕時(仍在下拉菜單的另一個子頁面上),它不會重新加載頁面上的內容,而是會更改URL。 使用Href時,它將正確加載所有內容。
<div
ngbDropdownMenu
class="dropdown-menu"
aria-labelledby="navbarDropdown">
<div *ngFor="let competentie of competenties">
<a
class="dropdown-item"
routerlink="/competenties/{{competentie.id}}">
{{competentie.name}}
</a>
</div>
</div>
這迫使我使用href而不是routerlink重新加載頁面,以便組件重新加載並顯示具有正確的{{competentie.id}}的內容。
有沒有一種方法可以使用routerlink導航到另一個下拉頁面並更新頁面上的內容?
詳細信息組件:
export class CompetentieComponent implements OnInit {
competentie: Competentie;
constructor(private route: ActivatedRoute,
private competentieService: CompetentieService,
private location: Location
) {
}
getCompetentie(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.competentieService.getCompetentie(id)
.subscribe(competentie => this.competentie = competentie);
}
ngOnInit() {
this.getCompetentie();
}
}
我的路線:
const routes: Routes = [
{path: 'competenties/:id', component: CompetentieComponent}
];
該服務從具有數組COMPETENTIES []的類獲取數據:
export class CompetentieService {
getCompetenties(): Observable<Competentie[]> {
return of(COMPETENTIES);
}
getCompetentie(id: number): Observable<Competentie> {
return of(COMPETENTIES.find(competentie => competentie.id === id));
}
constructor() {}
}
您正在使用this.route.snapshot.paramMap.get('id')
,它將僅觸發一次。 您應該使用params
而不是snapshot.paramMap.get('id')
。 params
是一個BehaviorSubject
訂閱對象,每次更改時,它都會為您提供更新的id
。
您應該將ActivatedRoute
注入為依賴項,然后在其上訂閱params
屬性。
export class CompetentieComponent implements OnInit {
competentie: Competentie;
constructor(private route: ActivatedRoute,
private competentieService: CompetentieService,
private location: Location
) {}
getCompetentie(): void {
this.activatedRoute.params.subscribe(params => {
let latestID = +params['id'];
this.competentieService.getCompetentie(latestID)
.subscribe(competentie => this.competentie = competentie);
});
}
ngOnInit() {
this.getCompetentie();
}
}
對於動態路由,請嘗試以下操作:
<a class="dropdown-item" [routerLink]="['/competenties/' + competentie.id]">
{{competentie.name}}
</a>
將此添加到您的代碼:
<a class="dropdown-item" [routerLink]="['/competenties/' + competentie.id]">
{{competentie.name}}
</a>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.