如何在路由或控制器中访问RESTAdapter的主机和命​​名空间? [英] How do you access RESTAdapter's host and namespace inside a route or controller?

查看:103
本文介绍了如何在路由或控制器中访问RESTAdapter的主机和命​​名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些我在一些控制器和路由内部使用的自定义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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆