Get current route name in Ember

2019-01-07 13:59发布

I need to get the current route name in my ember application; I tried this: Ember App.Router.router.currentState undefined but it doesn't work for me (there is probablig something i'm missimg...) I use Ember rc6 and I have a multilingual app; in the applicationRoute I detect the browser's language and I redirect to the correct page with:

this.transitionTo(userLang);

but I would like this to be executed only when user are on the home page, so something like this:

if (currentRoute == 'home'){
  this.transitionTo(userLang)
}

标签: ember.js
9条回答
闹够了就滚
2楼-- · 2019-01-07 14:40

Currently as of Ember 1.7.0 you can get the current route from within a route by calling this.routeName.

查看更多
何必那么认真
3楼-- · 2019-01-07 14:42

If you want to get current route in your component or controller you can inject routing service (routing: Ember.inject.service('-routing'))

(for more) and use:

this.get('routing.currentRouteName') or this.get('routing.currentPath')

Example with component and computed property:

import Ember from 'ember';

export default Ember.Component.extend({
  routing: Ember.inject.service('-routing'),

  checkMyRouteName: Ember.computed(function() {
    return this.get('routing.currentRouteName');
  })
})

Example with controller and computed property:

import Ember from 'ember';

export default Ember.Controller.extend({
  routing: Ember.inject.service('-routing'),

  checkMyRouteName: Ember.computed(function() {
    return this.get('routing.currentRouteName');
  })
})

Current route in your route you just need this.routeName

Example with route:

import Ember from 'ember';

export default Ember.Route.extend({
  checkMyRouteName() {
    return this.routeName;
  }
})
查看更多
老娘就宠你
4楼-- · 2019-01-07 14:44

You could observe the application's currentPath and set it to the current route accordingly when it changes:

App = Ember.Application.create({
  currentPath: '',
});

App.ApplicationController = Ember.Controller.extend({
  updateCurrentPath: function() {
    App.set('currentPath', this.get('currentPath'));
  }.observes('currentPath')
}),

This way you have access to the currentPath when ever you want with App.get('currentPath');

E.g.

if (App.get('currentPath') == 'home'){
  this.transitionTo(userLang);
}

Hope it helps.

查看更多
登录 后发表回答