如何使用ui-router更新路由而不在控制器上调用$ onInit

时间:2017-11-29 16:16:47

标签: angularjs angular-ui-router angular-components

我正在尝试在模式打开时动态更新视图上的URL /状态,以及在首次显示视图时自动打开模式。我正在使用1.x版本的UI路由器和AnguarJS组件。我遇到的问题是当我更新状态时,$onInit()被触发;换句话说,打开模态会导致打开第二个模态。

以下是我处理改变状态的方法:

showModal() {
  const modal = this.$uibModal.open({
    component: 'viewModal',
    size: 'lg'
  })
  const resetState = () => {
    console.log('resetting state ...')
    this.$state.go('.', {
      id: this.$state.params.id
    }, {
      inherit: false,
      notify: false,
      reload: false,
      location: 'replace'
    })
  }
  modal.opened.then(() => {
    console.log('opening ...')
    this.$state.go('.', {
      foo: 'bar'
    }, {
      notify: false,
      reload: false,
      location: 'replace'
    })
  })
  // The 'catch' is due to the promise being rejected with 'backdrop click'
  // when clicking on the background, though it doesn't always work, but
  // that's another issue entirely
  modal.closed.then(resetState).catch(resetState)
}

这是相关的$onInit()代码

if (this.$state.params.foo) {
  this.showModal()
}

这是路线的样子

export default function routing ($stateProvider) {
  $stateProvider
    .state({
      name: 'exampleView',
      url: '/example/{id}?foo',
      component: 'exampleComponent'
    })
}

我原本以为设置reloadnotify设置为false会阻止重新加载视图,但事实并非如此。有没有更好的方法来更新状态而不触发$onInit?我应该直接使用window.location吗?我希望用户能够在打开模式的情况下加载此视图。我不一定需要历史记录支持,因此我愿意在打开/关闭模式时删除更新URL,但我希望尽可能保留它。

1 个答案:

答案 0 :(得分:0)

修复结果相对简单,但需要一段时间才能找到。我更新了我的路由,看起来像这样

export default function routing ($stateProvider) {
  $stateProvider
    .state({
      name: 'exampleView',
      url: '/example/{id}?foo',
      component: 'exampleComponent',
      params: {
        foo: {
          dynamic: true
        }
      }
    })
}

根据docs,将参数设置为dynamic将阻止参数的任何更改触发状态更改。这类似于应用于状态声明的reloadOnSearch属性,但该属性已弃用。