EmberJS: change url for loading model (ember-data)

2019-03-18 19:15发布

问题:

I have problems with ember-data. For example, I've created a project at http://localhost/~me/test

In my project I've created a store and a model as follows:

... 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,
});

Now when I search (somewhere in my route) for a person like this

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

The http://localhost/persons?post_id=10 is called. This one does not exist of course. I would've expected something like http://localhost/~me/test/persons?post_id=10. Even better would be http://localhost/~me/test/persons.php?post_id=10 How can I change this url ?

回答1:

This is as of Ember Data Beta 3

To take care of the prefix, you can use the namespace property of DS.RESTAdapter. To take care of the suffix, you'll want to customize the buildURL method of DS.RESTAdapter, using _super() to get the original functionality and modifying that. It should look something like this:

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


回答2:

MilkyWayJoe is right, in your adapter you can define the namespace.

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


回答3:

This would work too:

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

Or if you want to use a namespace and .php path:

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'),
});

The plurals bit is to make sure Ember Data doesn't add an 's', e.g. person.phps