jancervinka
jancervinka

Reputation: 257

How to access query parameters from route in Ember 1.7

In 1.7 Ember should support Query Parameters. I have no problems using them in controller but I'd like to access them in Route, ideally in beforeModel hook but model hook would work as well.

The API docs mention a queryParam parameter for the beforeModel hook but if I try to use it, it is always undefined.

The Query Parameters guide seems to suggest that the query parameters should be accessible as a part of the first parameter to the model hook. But that is also undefined. See the code below for examples.

Is there a way to access the query parameters from Route?

Thank you for your help.

App.ApplicationRoute = Em.Route.extend({
   beforeModel: function(transition, queryParams){
       console.log(queryParams.test); //undefined at /?test=123
   },
   model: function(params){
       console.log(params.test); //undefined at /?test=123
   }
}); 

Upvotes: 23

Views: 25144

Answers (5)

vantony
vantony

Reputation: 513

In the latest version of ember (2.12 at the time of writing this answer), queryParams can be accessed in the model hook as follows:

import Ember from 'ember';

export default Ember.Route.extend({
    queryParams: {
        test: ''
    },
    model(params) {
        console.log(params.test);
    },
});

Observe that now both dynamic segment and queryParams are accessible via the params object. Since params is not available in the beforeModel hook, this solution works on when you have to access the queryParams in the model hook.

Upvotes: 7

iOS dev
iOS dev

Reputation: 470

In latest ember version you can get the value in Route as

import Ember from 'ember';
export default Ember.Route.extend({
  beforeModel(params){ 
      console.log(params.queryParams.test); //if the parameter contains test as the key
  }
});

This works only if the locationType is auto in your environment.js file.

Upvotes: 5

Ramy Ben Aroya
Ramy Ben Aroya

Reputation: 2423

By specifying the query params in the controller, params will contain them automatically

ApplicationController = Ember.Controller.extend({
  queryParams: ['test'],
  test: null
});

Upvotes: 8

Dhara Joshi
Dhara Joshi

Reputation: 407

If you want to access in didTransition action,

didTransition: (queryParams) ->
  console.log(@get('queryParams'))

Upvotes: -4

typeoneerror
typeoneerror

Reputation: 56958

Pretty sure it's a bug, but you can access them in the meantime via the transition object:

App.ApplicationRoute = Em.Route.extend({
   beforeModel: function(transition){
       console.log(transition.queryParams.test);
   }
}

Upvotes: 24

Related Questions