【问题标题】:angular - uirouter update optional param without reloadangular - uirouter 更新可选参数,无需重新加载
【发布时间】:2017-08-14 19:54:20
【问题描述】:

我有一个 angular 4 应用程序,它有多个接受可选参数的路由(ui-router)。

{ name: 'shirts', url:'/shirts/:color/:size, component: ShirtComponent }

这可行,但我想做的是通过单击按钮更改一些可选参数。无需重新加载整个页面。我正在寻找一种方法来更新 url 中的参数。

我花了好几个小时寻找解决方案,但是有很多 Angular 1 的答案,我从文档中没有得到任何更明智的答案。

我们将不胜感激。

【问题讨论】:

    标签: angular angular-ui-router


    【解决方案1】:

    尝试使用 dynamic 标志声明参数。

    根据文档

    当dynamic为真时,参数值的改变不会导致状态进入/退出。不会重新获取解析,也不会重新加载视图。

    https://ui-router.github.io/ng1/docs/latest/interfaces/params.paramdeclaration.html#dynamic


    此外,由于您希望参数是可选的,您需要使用 value 标志声明它们,即

    指定参数的默认值。这隐含地设置了这个 可选参数

    https://ui-router.github.io/ng1/docs/latest/interfaces/params.paramdeclaration.html#value

    所有参数应该看起来像

    { 
      name: 'shirts',
      url:'/shirts/:color/:size, 
      component: ShirtComponent,
      params: {
        color: {
          value: null,
          dynamic: true
        },
        size: {
          value: null,
          dynamic: true
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用Location API 的go/replaceState 方法,该方法属于@angular/common。他们只会替换浏览器history 而不会让路由器知道。

      import { Location } from '@angular/common';
      
      export class MyComponent {
          constructor(private location: Location) { }
          redirect(){
              this.location.go('/mypath');
              //OR
              //this.location.replaceState('/mypath');
          }
      }
      

      Demo Here

      【讨论】:

      • 感谢您的回复,但我正在寻找一种在不重新加载页面的情况下更新按钮点击(所有个人)的多个参数的方法。使用上面的解决方案,我只能走一条路,对吧?
      猜你喜欢
      • 2019-02-06
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 2014-08-08
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      • 2018-08-09
      相关资源
      最近更新 更多