emberjs:转发到当前路线和重置动态段



我有一些路由,例如:

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.如果您定义了动态段,则需要提供有效的值。否则,Ember将不允许进入路线。当您直接从URL尝试时,我不是如何为您制定foo/bar/的方式。
2.最好使用transitionTo方法的路由名称而不是直接URL。2.您可以尝试http://alexspeller.com/ember-diagonal/route/post,以更好地理解ember路由模型


beforeModel钩中,您可以检查传入param 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)
}

最新更新