EmberJS:重新转换到当前路线并重置动态段

时间:2017-08-30 13:40:35

标签: ember.js

我有一些路线定义如下:

Router.map(function() {
      this.route('foo', function() {
         this.route('bar');
         this.route('bar', {path: 'bar/:fooid'});
      });
      // ...
});

/foo/bar/:fooid中的动态细分是一个可以针对某些规则进行验证的ID。为简化示例,我们假设:fooid必须包含3位数字。

如果在/foo/bar/1234567中传递了无效值,我想将网址重置为foo/bar/

简化的foo.bar路线:

export default Ember.Route.extend({

  model (params) {
     // If fooid is invalid, set model.fooid.isValid to false
  },

  afterModel (model, transition) {
     // If fooid is invalid...
     this.transitionTo('/foo/bar/');
  }

});

验证过程本身有效但我无法摆脱网址中错误的:fooid参数!

如果我转换到其他路线,它可以正常工作。

Ember版本是2.14

1 个答案:

答案 0 :(得分:1)

我认为您需要使用默认索引路由,该路由将用于每条路由。

this.route('foo', function() {
    this.route('bar', function () {        
        this.route('child', { path: ":fooid" });
    });
});

此处为网址/foo/bar

route- app/routes/foo/bar/index.js  
controller - app/controllers/foo/bar/index.js  
template - app/templates/foo/bar/child.hbs 

以及网址/foo/bar/123

route- app/routes/foo/bar/child.js  
controller - app/controllers/foo/bar/child.js  
template - app/templates/foo/bar/index.hbs

如果您拥有上述结构,则可以从foo.bar.child转换为foo.bar.index路线。

app/routes/foo/bar/child.js的模型钩子中,您可以说this.transitionTo('foo.bar.index')。它会带你走那条路。

注意:
1.如果您定义了动态段,则需要提供有效值。否则ember将不允许进入该路线。当您直接从网址尝试时,我不是foo/bar/为您解决的问题 2.最好使用transitionTo方法的路由名称而不是直接URL。 2.您可以尝试http://alexspeller.com/ember-diagonal/route/post以更好地理解余烬路由模型

beforeModel挂钩中,您可以检查传入的参数fooid,如果它处于错误的状态,那么您可以使用默认值transitionTo

beforeModel(transition){
 // you can transition.params[transition.targetName].fooid to get the value.
 //then try transitionTo the same route with default value
 this.transitionTo('foo.bar',defaultValue)
}
相关问题