Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing custom ajax calls when loading data in model

Tags:

ember.js

In my Emberjs application I have an Employee model which I should load through a REST Get API call, where I have to authenticate the API first for a token then start loading the data, I know how to do this easily using JQuery but not sure how I can implement this in EmberJS, so I will appreciate it so much if anyone can instruct me how to do so.

Below is the JQuery code I use for authentication, extracting the employees data, as well as my EmberJS model code

Thanks

Authentication:

 $.ajax
  ({
    type: "POST",
    url: "http://portal.domainname.com/auth",
    dataType: 'json',
    async: false,
    data: JSON.stringify({ 
        Login: "[email protected]", 
        Password : "test"
    }),
    success: function(data) {
        console.log(data); //Here I get the token needed for further calls...
    },
    error: function(xhr, error){
        console.debug(xhr); console.debug(error);
    } 
});

Calls to load employees data:

$.ajax   ({
    type: "GET",
    url: "http://portal.domainname.com/employees",
    dataType: 'json',
    async: false,
    beforeSend: function (xhr) {
        xhr.setRequestHeader ("Token", "0000000-0000-0000-0000-00000000");
    },
    success: function(data) {
        console.log(data);
    },
    error: function(xhr, error){
        console.debug(xhr); console.debug(error);
    }  });

EmberJS Model

App.Store = DS.Store.extend({
  revision: 11
});

App.Employee = DS.Model.extend({
  employeeID:             DS.attr('string'),
  employeeName:        DS.attr('string')
});

App.Store.reopen({
 adapter: 'DS.RESTAdapter'
});
like image 300
MChan Avatar asked Mar 12 '26 08:03

MChan


1 Answers

You can add headers to all Ember AJAX requests like this:

App.Store = DS.Store.extend({
  revision: 13,
  adapter: DS.RESTAdapter.extend({
    ajax: function(url, type, hash) {
      if (!hash) {
        hash = {};
      }
      hash.beforeSend = function(xhr) {
        xhr.setRequestHeader("Authorization", "Token " + window.sessionToken);
      };
      return this._super(url, type, hash);
    }
  })
});

I use this code in production.

like image 61
Martin Avatar answered Mar 15 '26 19:03

Martin