17

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'
 });
Joe B
  • 1,261
  • 14
  • 20

1 Answers1

27

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();
 }
Joe B
  • 1,261
  • 14
  • 20
  • 1
    Use `get()`, to get host, `this.store.adapterFor('application').get('host')`. – denis.peplin Feb 25 '14 at 11:00
  • 1
    Note also that adapter takes a JS object as its first parameter, so if you want to specify a type use `{ typeKey: 'myModelType' }`, otherwise just leave it undefined to get application adapter. See also https://github.com/emberjs/data/blob/2a68c63a818da70b7f4ebf7a85a79e944532b209/packages/ember-data/lib/system/store.js#L1474-L1482 – Giovanni Cappellotto Jul 18 '14 at 10:34
  • 2
    nowadays you'll need to inject the store. `store: Ember.inject.service('store')` and then get it `this.get('store').adapterFor(...)` – Joe B May 31 '17 at 12:33