在Ember.js中如何从App.Router获取rootURL?

问题描述 投票:0回答:2

如何在我的控制器中的App.Router中获取rootURL以在我的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
         });
      }
    }
});
javascript ember.js ember-router ember-controllers
2个回答
1
投票

路由器注入到所有路由上,您可以将该操作移动到路由并从中获取路由器。

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


0
投票

以下代码适用于Ember 2.10(关于服务和组件):

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

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

© www.soinside.com 2019 - 2024. All rights reserved.