问题
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