【问题标题】:How to update route with ui-router without calling $onInit on controller如何使用 ui-router 更新路由而不在控制器上调用 $onInit
【发布时间】:2018-05-13 10:11:21
【问题描述】:

我正在尝试在打开模式时动态更新视图上的 URL/状态,并在首次显示视图时处理自动打开模式。我正在使用 1.x 版本的 UI Router 和 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,但如果可能的话我更愿意保留它。

【问题讨论】:

  • $onInit() 之前验证是否打开了模式以防止执行该操作
  • 我想过,但是 AngularUI 的(Bootstrap)模态类没有那个功能,所以我需要进入 DOM 并查看 body 标签上的类。当然可行,但不是很干净。我尝试在控制器上设置一个属性,但这在状态更改之间不会持续存在。
  • 重构代码以使模式从服务中运行。然后服务可以跟踪模态的打开/关闭状态。

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


【解决方案1】:

修复结果相对简单,但需要一段时间才能找到。我将路由更新为如下所示

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

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

【讨论】:

    猜你喜欢
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多