How to access dynamic segment in a controller in Ember.js?

前端 未结 4 1454
余生分开走
余生分开走 2021-02-14 01:07

I have an example route:

this.route(\'client\', {path: \':id\'});

I can access this in my route like this:

model: function(para         


        
相关标签:
4条回答
  • 2021-02-14 01:43

    There's a serialize function within the Route that you can take advantage of. Here's the API Documentation for it. However, in your context, you can just do this:

    App.IndexRoute = Em.Route.extend({
      model: function(params) {
        console.log(params.client_id);
      },
      serialize: function(model){
        return { client_id : model.id };
      }
    });
    

    Let me know if this works!

    I also noticed an error in your route definition. It should presumably be

    this.route('client', {path: '/:client_id'});
    

    or

    this.route('client', {path: '/client/:client_id'});
    
    0 讨论(0)
  • 2021-02-14 01:45

    If your id happens to be part of your model you can retrieve from the model itself. For example, if you have a route with an object Bill as a model, and the path bills/:billId, on your controller you can retrieve it this way:

    this.get('model').id

    0 讨论(0)
  • 2021-02-14 01:45

    I just came across this question since I too was wondering what was the best way to do this. I chose to go via the route of returning a hash from the model rather than setting parameters in the route.

    So in your case I would do the following:

    model() {
      Ember.RSVP.hash({client: <get client>, id: id});
    }
    

    And then in the controller or template I can access the client by calling

    model.client
    

    and get the id by calling

    model.id
    

    I personally feel this is a cleaner way of accessing the id as compared to setting a param on the route. Of course I am assuming that the id is not already set on the model. Otherwise this entire exercise is pointless.

    0 讨论(0)
  • 2021-02-14 01:58

    This is how I do it in my application. Not sure if this is the best approach.

    App.IndexRoute = Em.Route.extend({
      model: function(params) {
        this.set('params', params);
      },
      setupController: function(controller, model) {
        controller.set('params', this.get('params'));
        this._super(controller, model);
      }
    });
    

    Alternatively you can also do a lookup on the container inside your controller. But I dont really think this is a good approach. Here is an example.

    this.get('container').lookup('router:main').router.currentHandlerInfos
            .findBy('name','index').params
    
    0 讨论(0)
提交回复
热议问题