In Ember.js how can I get the rootURL from App.Router?

1.4k Views Asked by At

How can I get the rootURL in App.Router in my controller to use in my JSON request?

If I specify a rootURL like this:

App.Router.reopen({
  rootURL: '/site1/'
});

I want to be able to do something like this:

FooController = Ember.ObjectController.extend({
   needs: ["application"],
   actions: {
     examine: function() {
         var rootURL = this.get('controllers.application.router.rootURL');
         $.getJSON(rootURL + "/examine/" + id).then(function(response) {
         // do stuff with response
         });
      }
    }
});
2

There are 2 best solutions below

0
On BEST ANSWER

The router is injected onto all routes, you can move that action up to the route and grab the router off of that.

FooRoute = Ember.Route.extend({
   actions: {
     examine: function() {
         var rootURL = this.get('router.rootURL');
         $.getJSON(rootURL + "/examine/" + id).then(function(response) {
         // do stuff with response
         });
      }
    }
});

Or you can just add the property to the controller when the route is setting up the controller.

FooRoute = Ember.Route.extend({
  setupController: function(controller,model){
    this._super(controller, model);
    controller.set('rootURL', this.router.rootURL);
  }
});

Example: http://emberjs.jsbin.com/tomuhe/1/edit

0
On

The following code has worked for me on Ember 2.10 (on services and an components):

const router = Ember.getOwner(this).lookup('router:main'),
  rootURL = router.get('rootURL');

I should add that this is generally a bad idea, but maybe it helps you.