如何在EmberJS 2.2路由器中使用动态段?

tin*_*yaa 5 ember.js ember-router

我无法弄清楚如何在EmberJS的新路由器API中创建具有动态段的路由.我花了一个星期的时间来尝试很多东西,但它不起作用.我对自己感到非常沮丧,因为我已多次浏览文档,API和源代码,无法弄清楚如何使这项工作.我渴望得到帮助.

我正在尝试实现以下路线:

  • / profile /:userId - > index
  • / profile /:userId/activity - >活动页面
  • /资料/:用户名/ ...

我的路由器设置如下

App.Router.map(function() {
  return this.resource("profile", function() {
    this.route("index", { path: '/:userId' });
    this.route("activity", { path: '/:userId/activity' });
  });
});
Run Code Online (Sandbox Code Playgroud)

然后,每当我尝试与linkTo帮助程序链接时,我收到以下错误:Uncaught More objects were passed than dynamic segments

<li>{{#linkTo "profile.index" user}}overview{{/linkTo}}</li>
Run Code Online (Sandbox Code Playgroud)

如果我不包含该user对象,那么我会收到另一个错误Uncaught Error: assertion failed: Cannot call get with 'id' on an undefined object.(显然是因为没有对象可以获取该ID)

如果它是任何助手,这是我的路线声明

App.ProfileIndexRoute = Ember.Route.extend({
  model: function(params) {
    return Ember.Object.create({
      id: 1
    });
  },
  setupController: function(controller, model) {
    return controller.set("content", model);
  }
});

App.ProfileActivityRoute = Ember.Route.extend({
  model: function(params) {
    return Ember.Object.create({
      id: 1
    });
  },
  setupController: function(controller, model) {
    return controller.set("content", model);
  }
});
Run Code Online (Sandbox Code Playgroud)

Cra*_*den 4

JSBin 示例

您可以通过更多的嵌套来构建您的路由,以获得您想要的 URL(并且您不需要在路由器中包含 return 语句):

App.Router.map(function() {
  this.resource("profile", function() {
    this.resource("userprofile", { path: '/:userId' }, function() {
      this.route("index", { path: '/' });
      this.route("activity", { path: '/activity' });
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

然后像这样设置你的路线:

App.IndexRoute = Ember.Route.extend({
  model: function(params) {
    return [Ember.Object.create({
      id: 1
    })];
   }
});

App.UserprofileIndexRoute = Ember.Route.extend({
  model: function(params) {
    console.log("userindex route", params);
    return Ember.Object.create({
      id: 1
    });
  },
  setupController: function(controller, model) {
    return controller.set("content", model);
  }
});

App.UserprofileActivityRoute = Ember.Route.extend({
  model: function(params) {
    return Ember.Object.create({
      id: 1
    });
  },
  setupController: function(controller, model) {
    return controller.set("content", model);
  }
});
Run Code Online (Sandbox Code Playgroud)

您可以链接到该/profile/1页面:

{{#linkTo userprofile.index user}}
Run Code Online (Sandbox Code Playgroud)

或链接至/profile/1/activity页面:

{{#linkTo userprofile.activity user}}
Run Code Online (Sandbox Code Playgroud)