EmberJS Direct Slug URL Access Not Working

2019-09-02 09:27发布

I am using slugged URLs for cleaner URLs to convert from this:

http://mydomain.com/#/posts/1

to this:

http://mydomain.com/#/posts/first-awesome-post

The problem is that, if I were to directly access the page via direct slugged url (http://mydomain.com/#/posts/first-awesome-post), I got a blank page instead.

Here is what I have:

App.Router.map(function() {
    this.resource('posts', function() {
        this.resource('post', { path: ':post_id' });
    });
});

App.Post.FIXTURES = [{
  id: 1,
  name: 'First Awesome Post',
  slug: 'first-awesome-post'
}];

App.PostRoute = Em.Route.extend({
    model: function(params) {
        return App.Post.find(params.post_id);
    },

    setupController: function(controller, model) {
        this._super.apply(this, arguments);
    },

    serialize: function(model, params) {
        return { post_id: model.get('slug')};
    },
});

I have tried the following:

  • Replaced params.post_id in App.PostRouter to params.post_slug and entered the following URL to my browser http://mydomain.com/#/posts/first-awesome-post; Result: The page CSS and HTML loads but the data of id #1 did not load (i.e. model hook isn't called)
  • Got rid of serialize function and entered the following URL to my browser http://mydomain.com/#/posts/1; Result: Everything works fine (CSS, HTML, and data got loaded perfectly)

May I know what I have been doing wrong in this case?

P.S. I am currently using EmberJS version 1.0.0-rc.6

标签: url ember.js
1条回答
劳资没心,怎么记你
2楼-- · 2019-09-02 10:14

If you want to use the slug you should change the model function and make use of findQuery as you are seaching a model by an attribute other than id http://emberjs.com/api/data/classes/DS.Store.html#method_findQuery, but this function returns an RecordArray, you could use the setupController hook for setting the only one object of the array

App.Router.map(function() {
    this.resource('posts', function() {
        this.resource('post', { path: ':post_slug' });
    });
});

App.Post.FIXTURES = [{
  id: 1,
  name: 'First Awesome Post',
  slug: 'first-awesome-post'
}];

App.PostRoute = Em.Route.extend({
    model: function(params) {
        return App.Post.findQuery({slug:params.post_slug});
    },
    setupController: function(controller, model) {
    //If the model comes from a link-to helper it will be an object, if it comes from the route it will be an array of one element
      if(Ember.isArray(model)){
        controller.set('model',model.get('firstObject'));
      }
      else{
        controller.set('model',model);
      }
    },

    serialize: function(model, params) {
        return { post_slug: model.get('slug')};
    },
});
查看更多
登录 后发表回答