简体   繁体   English

Angular 2 在没有重定向的情况下更新 URL 路径参数

[英]Angular 2 updating URL path params with no redirect

Using Angular 2 how do you update the URL Path without redirecting the page.使用 Angular 2 如何在不重定向页面的情况下更新 URL 路径。

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.我知道您可以使用 ActivatedRoute queryParamMap Observable 访问参数,但是如果我想更改这些值并将这些值显示在 URL 中该怎么办。

Updating the values in the URL allows for easy bookmark-ability.更新 URL 中的值可以轻松添加书签。

I don't want to redirect as the query params I am adding are simple data filter I want to store.我不想重定向,因为我添加的查询参数是我想要存储的简单数据过滤器。

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 }});
}

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM