angular 路由重载,可变路由或参数变更如何重新加载

1,421 阅读1分钟

背景

如下的url https: // xxx.com/#/service/7?projectView=xxx

这么一种场景,一个URL中的参数变了 也就是projectName 的值变了,如果这时需要监测到这次变更,并重新加载当前页面内容,要怎么做呢。

读完这篇文章,希望能解答你这个问题。

解决方案

根节点app.module.ts 的路由提取出来,放在app-routing.module.ts中

1、在routes中增加 onSameUrlNavigation: 'reload' ,只有这一行并不能真正起作用。

@NgModule({
    imports: [
        RouterModule.forRoot(routes, {
            useHash: true,
            onSameUrlNavigation: 'reload'
        }),
    ]
})

2、还需要在对应的路由配置中增加 runGuardsAndResolvers: "paramsOrQueryParamsChange"

runGuardsAndResolvers 有三个参数paramsChange(可变路由变化) paramsOrQueryParamsChange(参数变化) always(总是)

const routes: Routes = [
    {
        path: 'service/:id',
        component: yourComponent,
        runGuardsAndResolvers: "paramsOrQueryParamsChange"
    }
}

3、最后在使用的组件中init增加一个事件监听

  ngOnInit() {
    this.subscription = this.router.events.pipe(
      filter(event => event instanceof NavigationEnd)
    ).subscribe((resp) => {
        // 这里是自己的要增加的代码处理逻辑
        this.id = this.activatedRoute.snapshot.queryParams['id'];
        this.getTableList();  
    })
  }
 ngOnDestroy(): void {
    this.subscription.unsubscribe(); // 不要忘记取消订阅
  }