0

如何在我的控制器中获取 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
         });
      }
    }
});
4

2 回答 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

于 2014-07-26T02:31:12.330 回答
0

以下代码在 Ember 2.10 上对我有用(在服务和组件上):

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

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

于 2017-01-24T16:03:06.590 回答