17

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)
}
Community
  • 1
  • 1
Cereal Killer
  • 3,387
  • 10
  • 48
  • 80
  • possible duplicate of [Emberjs - How to access the current state or route name in RC1?](http://stackoverflow.com/questions/15318981/emberjs-how-to-access-the-current-state-or-route-name-in-rc1) – givanse May 11 '14 at 16:01

11 Answers11

26

NOTE: as of Ember 3.16, the original answer is not only recommended, but observers are strongly discouraged.

To get the current route name, you can utilize the Router Service: https://api.emberjs.com/ember/3.18/classes/RouterService/properties/currentRouteName?anchor=currentRouteName

export default class MyComponent extends Component {
  @service router;

  get activeRoute() {
    return this.router.currentRouteName;
  }
}

Original answer below


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.

NullVoxPopuli
  • 61,906
  • 73
  • 206
  • 352
intuitivepixel
  • 23,302
  • 3
  • 57
  • 51
  • Well, the thing is that if i do 'console.log(App.get("currentPath"))' inside the controller, I can see that it works; but i need to access currentPath from inside the redirect method of the ApplicationRoute, and here it doesn't work (the console log here shows that currentPath has no value)... Probably currentPath is updated only after the redirect method is called... – Cereal Killer Aug 18 '13 at 22:19
  • Also doing everything from the controller works (so now i don't need the redirect method of ApplicationRoute anymore); thanks for help... – Cereal Killer Aug 18 '13 at 22:25
  • 4
    I'm trying to do this in the Ember App Kit, where the 'App' global namespace has been replaced with the ES6 module transpiler. Since App.set and App.get don't work, how do I access 'currentPath'? Thanks! – Chris Jan 16 '14 at 19:25
  • @intuitivepixel , Thanks, But I have observed that there is a problem with params. For example If I have: 'this.resource('detail', { path: '/detail/:type' }, function() {});' the currentPath is datail.index. I need to know the type. Can you help me? – vicenrele Feb 10 '15 at 15:54
26

This worked for me on 1.3.0-beta (and a quick glance at the source for 1.1.2 suggests it would work there too):

App.__container__.lookup('router:main').location.lastSetURL

Note that the documentation states:

At present, it relies on a hashchange event existing in the browser.

However, I believe it's strongly suggested that App.__container__ not be used in production code. A more acceptable alternative would be to use App.Router.router.currentHandlerInfos, which provides information on the current Ember route.

Yet another option is currentRouteName on the ApplicationController. You can add needs: ['application'] to your controller, then access the route name with controllers.application.currentRouteName. This will return something like posts.index.

Liam
  • 27,717
  • 28
  • 128
  • 190
Linda
  • 596
  • 5
  • 8
  • I can confirm that it works with 1.2.0. But you must be careful, it does not work after the initial load of the application, even if it is a deep link; only after making a transition, it will return the correct value. – vanthome Dec 11 '13 at 08:56
  • 7
    Not only does `App.Router.router.currentHandlerInfos` contain information about the current Ember route including its context (read: model), it also contains similar information for all parent routes. If you need these data, it really is the way to go! – nickiaconis Jan 28 '14 at 18:51
  • `App.__container__.lookup()` is tremendously useful. – datchung Jul 01 '15 at 15:50
18

With the shift to components, it is harder to get route name. The best way is to add an initializer such as

ember g initializer router

(from command line), and

export function initialize(application) {
  application.inject('route', 'router', 'router:main');
  application.inject('component', 'router', 'router:main');
}

export default {
  name: 'router',
  initialize
};

in a initializers/router.js. You can also inject into controller if you need to. Then just do simply

this.get('router.currentRouteName');

in JS, or

{{router.currentRouteName}}

in template.

This is the only way I have found to get it reliably, and observable in Ember 2.4

Xeridea
  • 1,146
  • 1
  • 10
  • 17
  • 1
    Very nice indeed sir – Nicolai Dahl Apr 26 '16 at 12:56
  • This worked for me in Ember 2.7, thank you so much! This was also helpful to understand what is going on - especially the last answer about watching the route for changes: http://discuss.emberjs.com/t/ember-get-current-route-name/10324/7 – rmcsharry Sep 08 '16 at 17:22
  • I used this info to help build this component: http://stackoverflow.com/questions/39395911/emberjs-2-7-how-to-bind-attribute-disabled-for-a-button/39396958#39396958 – rmcsharry Sep 08 '16 at 17:30
  • Injecting services by default is considered a bad practice in modern ember. You should define a service and inject it where needed. The `EmberRouter` is not even a service but just used as one here. I would strongly recommend to use `RouterService` added in Ember 2.15 instead. – jelhan Aug 15 '19 at 15:54
18

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('routing.currentRouteName',  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('routing.currentRouteName', 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;
  }
})
Charles
  • 11,367
  • 10
  • 77
  • 114
Hubert Olender
  • 1,130
  • 9
  • 15
  • 1
    You should not use private `-routing` service anymore. A public `RouterService` has been added in Ember 2.15 and is polyfilled for Ember >= 2.4. – jelhan Aug 15 '19 at 15:49
  • @jelhan Yes, you are right. I didn't update it. For example, now I am using 3.8 version and there is: import { inject as service } from '@ember/service'; router: service(), get(this, 'router.currentRouteName') Today I learned that I have to write which version I refer when I reply on StackOverflow, cause I even don't remember which version was when I wrote it :) – Hubert Olender Aug 28 '19 at 18:27
13

Just as an update, in Ember 1.8.1, we can get the routeName inside an Ember.Route object by doing this.routeName.

Gjaldon
  • 5,534
  • 24
  • 32
3

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

dannytenaglias
  • 343
  • 3
  • 6
3

The Ember namespace API now has a getOwner method, which is very useful for looking up the currentRouteName, or, other route properties.

  const owner        = Ember.getOwner(this);
  const currentRoute = owner.lookup('router:main').currentRouteName;
  const routeInfo    = owner.lookup(`route:${currentRoute}`).get('info');
  // etc.

I've created an Ember Twiddle example to demonstrate. Use the text input above the "Output" pane to hit other routes like /blue, /green, or /red.

jacefarm
  • 6,747
  • 6
  • 36
  • 46
  • 1
    Please note that `currentRouteName` property of `EmberRouter` is not only private but even [undocumented](https://api.emberjs.com/ember/3.12/classes/EmberRouter). You should use public [`RouterService`](https://api.emberjs.com/ember/3.12/classes/RouterService) instead, which was added in Ember 2.15 and is polyfilled for Ember >= 2.4. – jelhan Aug 15 '19 at 15:51
2

Ember has a RouterService since 2.15. It provides the name of the current route as currentRouteName property. A polyfill exists for Ember 2.4 - 2.14 if you are still on such an old version.

import Component from '@ember/component';

export default Component.extend({
  router: service(),

  isHomeRoute: computed('router.currentRouteName', function() {
    return this.router.currentRouteName === 'home';
  }),
});

All other solutions mentioned here are relying on private API that might already be deprecated / removed. Using RouterService is working at least up the current version, which is 3.12 at the time of writing this.

Please note that the "home" is not /. The root URL is called "index".

jelhan
  • 6,149
  • 1
  • 19
  • 35
0

I had the same problem for a while. then i started exploring router. It always have a state object which can be obtained from any route using

var route = this;
var handlerInfos = route.get("router.router.state.handlerInfos");
var currRouteHandlerInfo = handlerInfos[handlerInfos.length-1];
var currRouteName = currRouteHandlerInfo.name; //"home"

that's it. Now you have the current route name!

if you want the current route params,

var routerParams = this.get("router.router.state.params");
var currRouteParams = routerParams[currRouteName]; //{ homeId : "1" }
Mohan Kumar
  • 621
  • 1
  • 8
  • 25
0

this worked for me on the route.js file: this.controller.target.currentPath

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 02 '23 at 11:25
-2

You can simple parse the current URL. This way you can use your full url for example:

http://127.0.0.1:8000/index.html/#/home

and extract from this string the suffix:

/home

which is the current route name.

A simple JS function (that works regardless to your Ember version) will be:

function getCurrentRoute()
{
    var currentRoute;
    var currentUrl = window.location.href; // 'http://127.0.0.1:8000/index.html/#/home'

    var indexOfHash = currentUrl.indexOf('#');
    if ((indexOfHash == -1) ||
        (indexOfHash == currentUrl.length - 1))
    {
        currentRoute = '/';
    }
    else
    {
        currentRoute = currentUrl.slice(indexOfHash + 1); // '/home'
    }

    return currentRoute;
}

Example of use:

if (getCurrentRoute() == '/home')
{
// ...
}
Gil Epshtain
  • 8,670
  • 7
  • 63
  • 89