Angular2 this.router.navigate fires only once

只谈情不闲聊 提交于 2019-12-06 15:43:47

I am not sure why your route definition points to the same component:

{
    path: 'page',
    component: MyComponent
},
{
    path: 'page/:action',
    component: MyComponent
}

Why don't you create a separate component for page/:action route?

Here is something from the Routing and Navigation documentation on Angular.io.

Observable paramMap and component reuse In this example, you retrieve the route parameter map from an Observable. That implies that the route parameter map can change during the lifetime of this component.

They might. By default, the router re-uses a component instance when it re-navigates to the same component type without visiting a different component first. The route parameters could change each time.

I believe that this is your issue. You are not really changing the components. Rather, you are reusing the same component over and over again. And for that reason router is reusing the same component instance.

For that reason I would create a new component that handles the :action part of your route.

{
    path: 'page',
    component: MyComponent
},
{
    path: 'page/:action',
    component: IHandleActionPartHereComponent
}

Update

In your selectTab() function, what is the purpose of splitting along the question mark?

let route = this.router.url.split('?')[0];

Your route will not be appended as a query parameter, but rather it will be appended to the actual route as in http://something/page/a not http://something/?page/b or however you imagined this. The url property will return the url as determined by the router: /page/a or /page/b. The length of your result should be 0. Because of that your if part will always be false and no redirection will occur.

You can try this:

{ path: 'page', component: PageParentComponent,
        children: [
          { path: '', redirectTo: 'a', pathMatch: 'full'},
          { path: 'a', component: AComponent},
          { path: 'b', component: BComponent}
        ]
 }

in HTML

this.router.navigate(['page/a']); // or
this.router.navigate(['page/b']);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!