我在导航栏的下拉菜单中使用角度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重新加载组件的页面以重新加载并使用正确的{}显示内容 .
有没有办法导航到另一个带有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() {}
}
3 回答
您正在使用
this.route.snapshot.paramMap.get('id')
,它只会触发一次 . 您应该使用params
而不是snapshot.paramMap.get('id')
.params
是BehaviorSubject
订阅,每次更改时都会为您提供更新的id
.您应该将
ActivatedRoute
作为依赖项注入其中,然后在其上订阅params
属性 .请尝试以下动态路由:
将此添加到您的代码中: