【问题标题】:EmberJS: change url for loading model (ember-data)EmberJS:更改加载模型的 url (ember-data)
【发布时间】:2013-01-02 15:29:37
【问题描述】:

我遇到了 ember-data 的问题。例如,我在 http://localhost/~me/test

创建了一个项目

在我的项目中,我创建了一个商店和一个模型,如下所示:

... init stuff here ...

var attr = DS.attr;
App.Person = DS.Model.extend({
    firstName: attr('string'),
    lastName: attr('string'),
});

App.Store = DS.Store.extend({
    revision: 11,
    adapter: DS.RESTAdapter,
});

现在当我(在我的路线某处)搜索这样的人时

var person = App.Person.find(params);

http://localhost/persons?post_id=10 被调用。这个当然不存在。我会期待像 http://localhost/~me/test/persons?post_id=10 这样的东西。更好的是 http://localhost/~me/test/persons.php?post_id=10 如何更改此网址?

【问题讨论】:

  • 不确定 RESTAdapter 最近发生了多少变化,但它曾经有一个名为 namespace 的属性,因此您可以扩展适配器并设置资源的全局路径,在您的情况下会是namespace: '~/me/test'。我不知道它是否仍然有效,现在找不到他们放在哪里了。

标签: url ember.js http-status-code-404 ember-data


【解决方案1】:

这是 Ember Data Beta 3 的版本

要处理前缀,您可以使用DS.RESTAdapternamespace 属性。要处理后缀,您需要自定义DS.RESTAdapterbuildURL 方法,使用_super() 来获取原始功能并对其进行修改。它应该看起来像这样:

App.ApplicationAdapter = DS.RESTAdapter.extend({
    namespace: '~me/test',
    buildURL: function() {
        var normalURL = this._super.apply(this, arguments);
        return normalURL + '.php';
    }
});

【讨论】:

    【解决方案2】:

    MilkyWayJoe 是对的,在你的适配器中你可以定义命名空间。

    App.Adapter = DS.RESTAdapter.extend({
      namespace: '~/me/test'
    });
    

    【讨论】:

    • Thnx,使用命名空间修复了 url 的第一部分。 .php 后缀怎么样。如果我使用适配器“复数”配置,例如:“person:persons.php”,我还需要将返回的 json 的根元素更改为“persons.php”。现在我没有收到任何错误,但是从 App.Person.find() 返回的“人”是空的!
    • @JeanlucaScaljeri 您从 API 接收的 json 格式是什么? Ember 期望它是这样的 {resource_name: [{resource_id: 1,resource_column_2: "data", resource_column_n: "data"}]}
    • App.Person.find(params) 是异步的 :( 所以我会把这个问题移到其他线程上。所以唯一的事情(仍然与我原来的问题有关)如何添加后缀 .php ?
    • 我假设只是将 .php 添加到命名空间的末尾不起作用?您的应用程序中是否需要 .php 扩展名?为什么不直接重写 .htaccess 中的 URL,让你的裸 URL 指向 php 文件呢?它将使这项工作发挥作用,并且对最终用户来说更漂亮。
    • 没错,我只是想知道,在这一点上,如果我可以添加 .php 会更容易。
    【解决方案3】:

    这也可以:

    App.Person = DS.Model.extend({
        url: '~me/test/persons',
        firstName: attr('string'),
        lastName: attr('string'),
    });
    

    或者如果你想使用命名空间和 .php 路径:

    App.Adapter = DS.RESTAdapter.extend({
      namespace: '~/me/test',
        plurals: {
            "persons.php": "persons.php",
        }
    });
    
    App.Person = DS.Model.extend({
        url: 'persons.php',
        firstName: attr('string'),
        lastName: attr('string'),
    });
    

    复数位是为了确保 Ember Data 不添加“s”,例如person.phps

    【讨论】:

    • 我正在使用 ember-data 0.13,这似乎没有任何效果......知道为什么吗?
    猜你喜欢
    • 1970-01-01
    • 2015-11-13
    • 2014-06-10
    • 1970-01-01
    • 2013-11-22
    • 2013-05-09
    • 2017-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多