如何在路由或控制器中访问RESTAdapter的主机和命名空间? [英] How do you access RESTAdapter's host and namespace inside a route or controller?
问题描述
我有一些我在一些控制器和路由内部使用的自定义AJAX请求,例如:
var loginRoute = Ember.Route.extend({
actions:{
submitLogin:function(user,pass){
var data = {username:user ,密码:pass};
Ember。$。post('http://192.168.2.10/api/v1/login',data).then();
}
}
});
这个功能很好,但在开发的时候我可能会有一个不同的IP(比如改变路由器)
,我想要访问我扩展RESTAdapter时定义的URL(host + namespace),以便我只需要更改主机
和/或命名空间
一次,而不是我做一个自定义ajax请求的每个地方。
App.ApplicationAdapter = DS.RESTAdapter.extend({
host:'http://192.168.2.10',
namespace:'api / v1'
});
证明你可以从商店访问适配器新$ submitLogin $> c $ c>方法可能如下所示:
submitLogin:function(user,pass){
var data = {username:user,password:pass},
host = this.store.adapterFor('application')。get('host'),
namespace = this.store.adapterFor 'application')。namespace,
postUrl = [host,namespace,'login'] .join('/'); // http://192.168.2.10/api/v1/login
Ember。$。post(postUrl,data).then();
}
I have a few custom AJAX requests that I use inside of some controllers and routes, for example:
var loginRoute = Ember.Route.extend({
actions: {
submitLogin: function(user, pass) {
var data = { username: user, password: pass };
Ember.$.post('http://192.168.2.10/api/v1/login', data).then();
}
}
});
This works fine, but while developing I may have a different IP (e.g. changing routers)
and I'd like to be able to access the URL(host + namespace) I defined when I extended the RESTAdapter so that I only have to change the host
and/or namespace
once, instead of every place where I do a custom ajax request.
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'http://192.168.2.10',
namespace: 'api/v1'
});
turns out you can access the Adapter from the store via this.store.adapterFor('application')
The new submitLogin
method could look like this:
submitLogin: function(user, pass) {
var data = { username: user, password: pass },
host = this.store.adapterFor('application').get('host'),
namespace = this.store.adapterFor('application').namespace,
postUrl = [ host, namespace, 'login' ].join('/'); // http://192.168.2.10/api/v1/login
Ember.$.post(postUrl, data).then();
}
这篇关于如何在路由或控制器中访问RESTAdapter的主机和命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!