Datsik
Datsik

Reputation: 14824

How do I access the variable of a dynamic route in EmberJS

I've done

ember g route auth
ember g route auth/pending

Which then gave me :

app/
  routes/
    auth/
      pending.js
    auth.js

and my router has

  this.route('auth', function() {
    this.route('pending', { path: '/pending/:steamid/:token'});
  });

Which everything is fine, when I visit

http://localhost:4200/auth/pending/1/2

The page loads, but how do I access :steamid and :token outside of the model.

I'd like to use it so that I can set values in my session service

Like:

import Ember from 'ember';

export default Ember.Route.extend({
  session: Ember.inject.service(),

  steamID: this.get(// Params Some How),
  token: this.get(// Params some How)

  thing(params) {
    this.get('session').set('tokenID', token),
    this.get('session').set('steamID', steamID)
  }
});

^^ Pseudo code to express what I'm trying to accomplish.

Upvotes: 0

Views: 591

Answers (2)

George Karanikas
George Karanikas

Reputation: 1244

You can set them in your service from many different hooks:

import Ember from 'ember';

export default Ember.Route.extend({

  session: Ember.inject.service(),

  /* Access from beforeModel */
  beforeModel(transition) {
    this.get('session').setProperties({
      tokenID: transition.params.token,
      steamID: transition.params.steamid
    });
  },

  /* Access from model */
  model(params, transition) {
    this.get('session').setProperties({
      tokenID: params.token,
      steamID: params.steamid
    });
  }
});

If you ask me model hook is the best choice. Especially if you want your query params to refresh the model every time they change (see guide).

Upvotes: 0

Terseus
Terseus

Reputation: 2212

While it's not in the website documentation, looking at the source code of the Transition object passed to some Route hooks (e.g. afterModel and beforeModel) it have a params property which contains the dynamic segment params.

So you can, for example:

import Ember from 'ember';

export default Ember.Route.extend({
    session: Ember.inject.service(),
    thing(params) {
        // Do some check and returns the result
    },
    beforeModel (transition) {
        if (!this.thing(transition.params)) {
            transition.abort();
            this.transitionTo('/login');
        }
    }
});

Upvotes: 1

Related Questions