Obtaining the current url using the Router service

#1

Hi,

I want to grab the (full) url in my (page) router so I can pass it to my server in order to produce navigation breadcrumbs.

In the page route, I am injecting the Router service, and am trying to grab the currentURL in the setupController method - but this just returns null.

import {inject as service} from '@ember/service';

Router …

export default Route.extend({
    router: service(),
    ...etc.etc

   setupController(controller,model) {
       this._super(controller,model);
       console.log(this.router.currentURL); // returns null
       console.log(this.router.get('currentURL')); // returns null
   }
});

Looking at the object (this.router) in the console I’m not sure why I can’t get this value?

Many thanks

1 Like
#2

I have the same problem.

#3

Maybe window.location?

#4

You can obtain the current url using the router service if you’re in a component, but I am struggling to do the same when in a route (as per the original question).

#5

If it’s just the url you need then plain ol JS will get you the url in the route

window.location.href 
#6

I made a twiddle to demonstrate how one might use the router service to get the URL: https://ember-twiddle.com/e0488ad92af7ce0d6a99f85e7fb73bcf?openFiles=routes.my-route.js%2C&route=%2Fmy-route

Here is the relevant working code from the twiddle

import Controller from '@ember/controller';
import { computed } from '@ember/object';
import { inject as service } from '@ember/service';

export default Controller.extend({
  router: service(),
  
  currentURL: computed('router.currentURL', function() {
    return this.router.currentURL;
  }),
});

or in native JS

import Controller from '@ember/controller';
import { inject as service } from '@ember/service';

export default class MyController extends Controller {
  @service router;
  
  get currentURL() {
    return this.router.currentURL;
  }
}

I did initially try to do what you were doing in your sample code, by trying to access the currentURL in the route, and also received null. It turns out that this is because the currentURL is the previous route. The currentURL property cannot be the URL for the route, because while the lifecycle hooks within the route are being invoked, the route transition has yet to complete, and only when the route transitions successfully will the currentURL reflect the route path.

Hope this makes sense! :slight_smile:

#7

Hi - that’s great thank you - very helpful!