简体   繁体   中英

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

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
         });
      }
    }
});

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM