如何在一条路线及其子路线中拥有两个不同的模型?

How to have two different models within a route and its subroute?

我正在用 Ember 制作一个简单的网络聊天系统。

我有一个路由 /chatrooms 列出了几个聊天室,然后我还有 /chatrooms/:chatroom_id 应该显示带有消息的实际聊天室。

第二条路线在第一条路线之内,像这样:

this.resource('chatrooms', function() {
  this.route('show', {
    path: ':chatroom_id'
  });
});

当我访问 /chatrooms 时,调用服务器 (/api/chatrooms) 返回并显示房间列表,如预期的那样。

当我单击一个房间时,应用程序会转换到 /chatrooms/id,但不会调用来检索消息(在 /api/chatrooms/id 可用),即使我尝试定义模型也是如此。

我和用户有类似的情况。检索用户列表,然后显示。单击名称时,将显示配置文件。没有进行第二次调用,但这没关系,因为 Ember 已经知道用户的一切。

在我目前的例子中,当第一次返回列表时,它包括除消息之外的所有信息。我认为否则会太多(10 个聊天室 * 100 条最后的消息 = 每个请求在我的 JSON 中有 1000 个元素)。所以我只想在选择聊天室时调用服务器消息。

你知道怎么做吗,或者我一开始就做错了什么?

更新

来自 app/templates/chatrooms.hbs

的模板代码
<h1>Chatrooms</h1>
<ul class="sub-menu nobullet flex mas">
    {{#each chatroom in model}}
        <li class="mrs">{{link-to chatroom.name "chatrooms.show" chatroom class="pat"}}</li>
    {{/each}}
</ul>
{{outlet}}

在本例中,模型是聊天室数组。

我的路线:

app/routes/chatrooms.js

export default Ember.Route.extend({
  model: function() {
    return this.store.find('chatroom');
  }
});

app/routes/chatrooms/show.js

export default Ember.Route.extend({
  model: function(params) {
    return this.store.get('chatroom', params.chatroom_id);
  },
  actions: {
    send: function() {
      ...
    }
  }
});

正如在 this thread 中所讨论的,当您 link-to 一条路线并且模型已经加载时,路线的 model 挂钩不会被触发,因为不需要重新加载数据。

If you transition to a route and all the context objects -the objects which will serve as models to templates- are passed in, the beforeModel and model hooks will not be called.

稍后在线程 balint corrects:

In fact, the beforeModel hook still gets called in that case, it is only the model hook that does not.

如果您想强制重新加载模型,您可以更改 link 以使用 ID 而不是模型:

{{link-to chatroom.name "chatrooms.show" chatroom.id class="pat"}}

您还可以在 beforeModelafterModel 挂钩或 setupController.

中加载数据

此外,在 chatrooms/show 路由中,您将从 Ember 数据存储中获取已加载的模型,而不是从服务器加载它。试试这个:

return this.store.find('chatroom', params.chatroom_id);

我最后在聊天室的 JSON 响应中添加了 links 属性。当必须显示聊天室的内容时,使用 link 并检索消息。只需要两次请求,不需要预加载来自所有聊天室的所有消息,也不需要为每条消息都请求。