使用新的ui-router 1.0.0-rc.1延迟加载状态

时间:2017-03-15 14:06:04

标签: angularjs webpack angular-ui-router angular-ui-router-extras

我试图在gulp webpack设置中升级到ui-router 1.0.0-rc.1。我无法弄清楚如何从服务器加载状态并为其注册未来状态。

我想要实现的是landing父州。状态将从服务器加载,服务器是一组状态,如landing.<state-name>

  $stateProvider
    .state('landing', {
      url: '/',
      abstract: true,
      component: 'landing',
    })
    .state('landing.**', {
      url: '/',
      lazyLoad: function (transition) {
        return transition.injector().get('$http').get('/getStates').then(function (result) {
          var arr = [];
          angular.forEach(result, function (state) {
              arr.push({
                name: 'landing.' + state.state_name,
                url: state.url,
                templateUrl: state.partial_path
              });
          });
          return arr;
        });
      }
    })

我可以在控制台中看到以下内容。

Transition #0 r0: Started  -> "Transition#0( ''{} -> 'landing.**'{"remainder":"dashboard"} )"
[Violation] Long running JavaScript task took 284ms
trace.js:192 Transition #0 r0: <- Rejected "Transition#0( ''{} -> 'landing.**'{"remainder":"dashboard"} )", reason: TransitionRejection(type: 2, message: The transition has been superseded by a different transition, detail: 'landing.**'{"remainder":"dashboard"})
trace.js:150 Transition #1 r0: Started  -> "Transition#1( ''{} -> 'landing.**'{"remainder":"dashboard"} )"
trace.js:199 Transition #1 r0: <- Success  "Transition#1( ''{} -> 'landing.**'{"remainder":"dashboard"} )", final state: landing.**
stats.js:103 Font Awesome CDN reporting has been enabled

文档缺乏清晰度,所以,我有点卡住了。

任何帮助表示赞赏

1 个答案:

答案 0 :(得分:1)

https://ui-router.github.io/ng1/docs/latest/interfaces/ng1.ng1statedeclaration.html#lazyload

  

它应该返回一个LazyLoadResult。通常,其中一个延迟加载状态应与未来状态具有相同的名称。然后,新州将替换注册表中的未来州占位符。

未来的状态应该被延迟加载的同名状态所取代。懒惰加载'landing'状态(急切加载未来状态)。

https://ui-router.github.io/ng1/docs/latest/interfaces/state.lazyloadresult.html

  

如果你的州有一个lazyLoad函数,它应该返回一个promise。如果promise解析为与此接口匹配的对象,则StateDeclaration对象的states数组将自动注册。

您的承诺返回的对象应具有states属性

$stateProvider
.state('landing.**', {
  url: '/',
  lazyLoad: function (transition) {
    let $http = transition.injector().get('$http');
    return $http.get('states.json').then(function (result) {
      var arr = [];
      angular.forEach(result.data, function (state) {
        arr.push({
          name: state.state_name,
          url: state.url,
          templateUrl: state.partial_path
        });
      });
      return { states: arr }; // should have a "states" property
    });
  }
})

states.json:

[
  { "state_name": "landing", "url": "/", "partial_path": "landing.html" },
  { "state_name": "landing.foo", "url": "foo", "partial_path": "foo.html" },
  { "state_name": "landing.bar", "url": "bar", "partial_path": "bar.html" },
  { "state_name": "landing.baz", "url": "baz", "partial_path": "baz.html" }
]

这里是一名工作人员:http://plnkr.co/edit/BMNp0lbqI6Qw2zeEAvs1?p=preview