EmberJS:重新过渡到当前路线并重置动态段

EmberJS: Retransition to current route and reset dynamic segment

我定义了一些路由,例如:

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 那样传递了无效值,我想将 url 重置为 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/');
  }

});

验证过程本身有效,但我无法摆脱 url!

中错误的 :fooid 参数

如果我转换到不同的路线,它工作正常。

Ember 版本为 2.14

我认为你需要使用默认的索引路由,它会出现在每条路由上。

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

此处为URL/foo/bar

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

和 URL /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.If 您定义了动态细分,然后您需要提供有效值。否则 ember 将不允许进入路由。当您直接从 URL.
尝试时,我不知道 foo/bar/ 是如何为您计算出来的 2.Its 最好使用 transitionTo 方法的路由名称而不是直接 URL。 2. 你可以试试http://alexspeller.com/ember-diagonal/route/post来更好的理解ember路由模型


beforeModel hook中,可以检查传入的参数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)
}