【问题标题】:EmberJS 2 route dynamic segment in not nested routes undefinedEmberJS 2在未定义的嵌套路由中路由动态段
【发布时间】:2016-10-26 14:59:32
【问题描述】:

对 ember 非常陌生,并尝试设置基本(在我看来)路线。

我有 calendars 资源,我想显示单个日历。

我的app/router.js 有以下内容:

this.route('calendar', {path: 'calendars/:calendar_id'}, function () {
    this.route('show');
    this.route('edit');
});
this.route('calendars', function(){
    this.route('create');
});

文件夹如下:

app/routes: [
  calendars: [create, index],
  calendar: [edit, show]
]
app/templates: [
  calendars: [create, index]
  calendar: [edit, show]
]

app/routes/calendar/show.js:

import Ember from 'ember';
export default Ember.Route.extend({
    model(params) {
        return this.store.findRecord('calendar', params.calendar_id);
    }
});

当我转到http://SERVER/calendars/5/show 时问题就开始了(5 是 :calendar_id 部分,SERVER 是托管 ember 应用程序的部分):

  • 当我记录 params - 它们是未定义的
  • 在开发工具中,我看到 Ember 以某种方式向我的服务器发出 POST 请求,名称为 http://SERVER/calendars/5 (一个 :calendar_id 部分,SERVER 在同一个域上,并且我的后端所在的位置)。
  • 无论我是否在 app/routes/calendar/show.js 文件中注释掉 model() 函数,都会发生这种情况。
  • 显然 Ember 知道该请求使用什么 calendar_id
  • 但我不知道对服务器的调用发生在哪里:

    • 如果我完全注释掉 model(){},我的模板会呈现模型记录(Ember 获取的日历记录)。
    • 另一方面,如果我尝试在 model() 中记录 params 并注释掉 this.store.findRecord 部分,则 params 未定义并引发错误.
  • 起初我以为它是我的 DS.RESTAdapter,因为我已将 updateRecord 更改定义为假 PUT 请求(我的服务器不允许这样做),但我注释掉了整个文件,它仍然执行此查询。

  • 我已经清理了 dist/tmp/,升级到了 2.9.0,但效果相同。
  • 我没有定义控制器

如果路由中缺少 model() 钩子,Ember 如何发出 POST 请求,我没有定义控制器。另外我该如何修复它以使其正常工作? ;p

编辑[2]

我现在正在尝试这个,我认为它有点工作,但看起来很难看:

this.route('calendars',{ path: '/calendars'}, function(){
    this.route('create');
});
this.route('calendar', { path: '/' }, function () {
    this.route('show', { path: '/calendars/:calendar_id/show' });
    this.route('edit', { path: '/calendars/:calendar_id/edit' });
});
this.route('index', { path: ''});

【问题讨论】:

    标签: javascript ember.js


    【解决方案1】:

    Ember 足够聪明,可以在您不创建默认路由时生成默认路由,如果您不创建模型函数,则会生成默认模型。

    它根据路线名称执行此操作,即如果您的路线是“日历”,它会根据“日历”模型生成模型函数。

    尝试根据 ember 文档使用参数明确定义您的路由路径: https://guides.emberjs.com/v2.9.0/routing/defining-your-routes/

    this.route('calendar', function () {
        this.route('show', { path: '/:calendar_id/show' });
        this.route('edit', { path: '/:calendar_id/edit' });
        this.route('create');
    });
    

    【讨论】:

    • 我明白了。但是,我已经定义了 app/models/calendar.js 模型。但是,我没有定义任何控制器。尝试此设置会查找正在设置的 /calendars/:calendar_id/:calendar_id/show 路由。从中删除 /:calendar_id 会让我回到同样的问题。
    • 为了澄清它在路由中生成模型函数而不是模型本身
    • 我编辑了示例以从父路由中删除路径,因此它们现在仅在嵌套路由中
    • 是的,这样就可以了,它会创建一个类似/calendar/:calendar_id/show 的路由。但我想拥有像 /calendars/:calendar_id/show/calendars/create 这样的它而不嵌套这些路由。我不知道我是否偏离了某个约定,但我想在/calendars 下保持一致,因为在我看来它会显示该页面上的所有日历。
    • 无论哪种方式都可以,我建议嵌套,因为它允许您拥有更符合 SPA 意识形态的“基本”日历路线和模板。我重新编辑以更简洁的方式包含创建
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 2021-03-14
    相关资源
    最近更新 更多