Angular rc3路由器 - 使用不同的参数导航到同一页面

kLa*_*Lai 9 routing angular

我目前正在尝试使用不同的id值导航到同一页面.因此,如果我在浏览器更新中/test/1转到/test/2URL,但视图不刷新.我调试了ngOnInit,导航时没有重新运行/test/2.但是,如果我走的时候test/1other路由工作正常,只是导航到不同的参数相同的路由时出现的问题.还有其他人遇到过这个吗?当我得到一些时间生病上传一个plunkr.

Angular 2 rc3路由器 3.0.0-beta.2

RouterConfig = [
    {
        path: '',
        component: 'Layout',
        children: [
            {
                path: 'test/:id',
                component: TestComponent
            },
            {
                path: 'other',
                component: OtherComponent
            }
        ]
    }
]
Run Code Online (Sandbox Code Playgroud)

谢谢,LL

Arp*_*wal 15

当您使用不同的param导航到相同的路径时,它会重用该组件.因此ngOnInit不会再被召唤.您应该订阅routeparam in ngOnInit,然后在订阅的函数中执行视图更新

在构造函数中注入激活的路由

constructor(
  private route: ActivatedRoute,
  private router: Router,......) {}
Run Code Online (Sandbox Code Playgroud)

在该ngOnInit方法中,我们使用ActivatedRoute服务来检索路由的参数

ngOnInit() {
  this.sub = this.route.params.subscribe(params => {
     let id = +params['id']; // (+) converts string 'id' to a number
     //here goes your logic like below
this.service.getHero(id).then(hero => this.hero = hero);
   });
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅 "获取路径参数"部分