如何在我的控制器中的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
});
}
}
});
路由器注入到所有路由上,您可以将该操作移动到路由并从中获取路由器。
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);
}
});
以下代码适用于Ember 2.10(关于服务和组件):
const router = Ember.getOwner(this).lookup('router:main'),
rootURL = router.get('rootURL');
我应该补充一点,这通常是一个坏主意,但也许它可以帮助你。