Angular 2 updating URL path params with no redirect

点点圈 提交于 2019-12-24 08:51:03

问题


Using Angular 2 how do you update the URL Path without redirecting the page.

I know you can access the params using ActivatedRoute queryParamMap Observable but what if I want to change these values and have those display in the URL.

Updating the values in the URL allows for easy bookmark-ability.

I don't want to redirect as the query params I am adding are simple data filter I want to store.


回答1:


In the component constructor subscribe the query parameter to your model.

this.route.queryParams.subscribe(params => {
  this.myValue = params['myValue'];
});

Now, register a listener function to the view model, or alternatively add a watch to your model. Then have a navigate function you can call once your model is updated:

navigate() {
    this.router.navigate([], {queryParams: { mValue: this.myValue }});
}



回答2:


Just have the same component for two different routes

const appRoutes: Routes = [
    { path: 'somepath', component: someComponent }, // yourapp/somepath
    { path: 'anotherpath', component: someComponent }, // yourapp/anotherpath
];
<a class="nav-link" routerLink="/anotherpath" routerLinkActive="active"> change path</a>


来源:https://stackoverflow.com/questions/48787379/angular-2-updating-url-path-params-with-no-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!