我有一个带有RouterLink元素的锚元素,它接受参数。这些参数是导航到正确页面所必需的。现在,当我从不同的路径导航页面时,路由器链接正常工作。例如,我的路由器模块如下所示:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MoviesComponent } from './movies/movies.component';
import { MovieReviewComponent } from './movie-review/movie-review.component';
import { LoginComponent } from './login/login.component';
import { AdminComponent } from './admin/admin.component';
const routes: Routes = [
{ path: '', component: MoviesComponent },
{ path: 'movies', component: MoviesComponent },
{ path: 'movies/:movieTitle/:year', component: MovieReviewComponent },
{ path: 'login', component: LoginComponent },
{ path: 'admin', component: AdminComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
我在路由器插座外面有一个导航组件,如下所示:
<app-navigation></app-navigation>
<app-messages></app-messages>
<div id="main-layout" class="row p-3">
<section class="col-12 col-xm-12 col-md-3">hi</section>
<section class="col-12 col-xm-12 col-md-6">
<router-outlet></router-outlet>
</section>
<section class="col-12 col-xm-12 col-md-3">lo</section>
</div>
我的导航有一个搜索栏,它使用RouterLink路由到路径'movies/:movieTitle/:year'
并且只要我来自不像'movies/:movieTitle/:year'
的路径就可以使用。如果路径类似,即使movieTitle和year参数不同,angular也不会重新渲染。
例如,如果我在家'/'
或'movies'
,我可以使用导航栏成功转到'movies/The%20Dark%20Knight/2008'
。但是,如果我'movies/The%20Dark%20Knight/2008'
,我就无法使用导航栏转到'/movies/Taken/2008'
。我相信这与Angular试图减少类似路径的重新渲染有关,但是当相同的路径类型具有不同的参数时,如何让Angular更改视图?
额外信息
答案
正如答案所说,我需要订阅params。以前当我收到params时,我正在使用快照:
movieTitle = this.route.snapshot.paramMap.get('movieTitle');
现在我直接得到params并订阅它们:
this.route.params.subscribe(params => {
this.movieService.getMovie(params['movieTitle'], params['year'])
.subscribe(movie => {
this.movie = movie
})
})
答案 0 :(得分:2)
路径为空且没有孩子的路线应该有pathMatch:'full'
{ path: '', component: MoviesComponent, pathMatch: 'full' },
路线的顺序也很重要。 应该首先采用更具体的路线:
{ path: 'movies/:movieTitle/:year', component: MovieReviewComponent },
{ path: 'movies', component: MoviesComponent },
如果只有路由参数发生变化,但路由保持不变,则Angular会重用该组件。您需要订阅params以获得有关更改的通知。该URL仍在更新中。
答案 1 :(得分:0)
正如@Günter Zöchbauer
在他的回答中所说,您需要订阅params
才能获得有关更改的通知。这是您可以做到的...
假设您在OrderDetailComponent
中,并且想要显示特定订单的详细信息,则该ID为/orders/1
的URL中存在的ID的订单,如果ID更改,则正确显示正确的订单像/orders/2
,/orders/3
一样,...这是执行该操作的代码...
// order-detail.component.ts file
export class OrderDetailComponent implements OnInit {
constructor(private activatedRoute: ActivatedRoute) { }
ngOnInit() {
// Subscribing to the route params is important as it fixes an issue as
// Angular RouterLink may not work with same path but different params
this.activatedRoute.params.subscribe(params => {
console.log('URL Params', params);
this.getOrder(+params.id);
});
}
getOrder(id: number) {
// Your code to get the order with the provided id...
}
}