Reputation: 591
I am beginner at emberjs, I want to access url params in component but don't know how it is done in ember js.
I could get url params in route with code below:
model(params) {
this.store.query('ticket', {
page: {
number: params.page,
size: params.size
}
});
},
queryParams: {
page: {
refreshModel: true
},
size: {
refreshModel: true
}
}
Upvotes: 6
Views: 7497
Reputation: 1590
The quick answer:
You can inject the router into the component where you need it like this:
import Ember from 'ember';
const { computed: { alias }, observer } = Ember
export default Ember.Component.extend({
routing: Ember.inject.service('-routing'),
params: alias('routing.router.currentState.routerJsState.fullQueryParams')
})
Here is a twiddle with this implemented.
The longer answer:
You're using the injecting routing which is private, and using routerJsState.fullQueryParams like that is not really standard practice.
Because a query param is really a property somewhere, if you can make that "somewhere" a service, it would be better, because then you can inject that service into your component instead of routing like we do now. For example page and limit can live on a service and be injected into a controller and component, and would be a nicer solution.
Here is that solution in a twiddle.
The relevant code:
services/task-pager.js
import Ember from 'ember';
export default Ember.Service.extend({
page: 0,
limit: 3,
nextPage: function() {
this.set('page',this.get('page') + 1)
console.log(this.get('page'))
},
previousPage: function() {
this.set('page',this.get('page') - 1)
}
})
// controllers/tasks.js
export default Ember.Controller.extend({
taskPager: Ember.inject.service(),
queryParams:['page', 'limit'],
page: Ember.computed.alias('taskPager.page'),
limit: Ember.computed.alias('taskPager.limit'),
actions: {
nextPage: function() {
this.get('taskPager').nextPage()
},
previousPage: function() {
this.get('taskPager').previousPage()
}
}
})
//components/display-qp.js
export default Ember.Component.extend({
params: Ember.inject.service('task-pager')
})
//templates/components/display-qp.hbs
COMPONENT PARAMS PAGE:{{params.page}}
Upvotes: 9