在Ember.js中,我如何从App.Router中获得rootURL ?

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

本文关键字:Router App rootURL js Ember      更新时间:2023-09-26

我怎么能得到rootURL在App.Router在我的控制器在我的JSON请求中使用?

如果我这样指定一个rootURL:

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

我希望能够做这样的事情:

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

路由器被注入到所有的路由中,你可以把这个动作移到路由中,并从路由中抓取路由器。

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

或者你可以在路由设置控制器的时候把这个属性添加到控制器中。

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

示例:http://emberjs.jsbin.com/tomuhe/1/edit

以下代码在Ember 2.10(服务和组件)上运行:

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

我应该补充说,这通常是一个坏主意,但也许它会帮助你。