问题描述:点击某个组件后,组件参数变了,url变了,但是页面没有刷新。
例如: http://localhost:4200/#/test/data-testd/aaaaaaaaaaaa 后面参数变成http://localhost:4200/#/test/data-test/bbbbbbbbbbbb 页面没有刷新,需要手动刷新。
解决方案:
(方案 1)配置组件监听,监听到路径参数变化就刷新
① 添加 onSameUrlNavigation 属性
@NgModule({
imports: [
RouterModule.forRoot(routes, {
onSameUrlNavigation: "reload",
}),
],
exports: [RouterModule],
})
② 监听 NavigationEnd 事件:订阅 Router Event,在 NavigationEnd 中重新加载数据,销毁组件时取消订阅
import { Router, ActivatedRoute, NavigationEnd } from "@angular/router";
export class TestComponent implements OnInit {
public navigationSubscription;
constructor(
private activeRouter: ActivatedRoute,
private router: Router
) {
// 监听相同路由路径时刷新页面
this.navigationSubscription = this.router.events.subscribe((event: any) => {
if (event instanceof NavigationEnd) {
// 根据具体的场景来调用 ngOnInit 方法刷新页面
const url = event.url;
const newTestTag = url.lastIndexOf("?");
if (newTestTag > -1) {
this.ngOnInit();
}
}
});
}
ngOnInit(): void {
// ......
}
ngOnDestroy(): void {
if (this.navigationSubscription) {
this.navigationSubscription.unsubscribe();
}
}
}
(方案 2)先访问一个空路径 "/",再访问目标路径
testThrough(index: string) {
this.router
.navigateByUrl("/", { skipLocationChange: true })
.then(() =>
this.router.navigate([
this.userProvider.getMoudleName() + "/data-test/" + index,
])
);
}
不建议使用此方法,因为某些情况下如果空路径配置了默认路由,且此路由页面颜色鲜艳,这样页面会有闪一下,比较突兀。