How to generate an object in Ember.js store from JSON from backend side?

Question:

There is a rest controller on the Spring side, which sends a JSON response on a GET request. JSON is complex (contains nested objects).

On the frontend side of Ember.js, which should accept a JSON response and form an object in the store. The structure of the models in ember is completely the same as the json structure from spring, including the links.

As a result, nested objects are not generated on the ember side, only simple fields.

createObject() {
  var _this = this;
  $.getJSON('http://localhost:8080/object/getCard?id=24').then(function (response) {
    console.log(response);
    _this.store.createRecord('cards/object/card', response);
  });
}

JSON example:

{
    "id":24,
    "fullName":"qwerty",
    "form":"zzzzzzzzzzzz",
    "leader":
                {
                    "id":23,
                    "fullName":"testName test",
                    "email":"emailTest"
                }
}

The leader model is not populated.

How to properly map complex objects in Ember.js?

Answer:

Good afternoon. Maybe you can send a request to the server using your method, but I think they don’t do that.

You have to send a request to the server through the store.

You should have a model ready in ember, as they write here . You have a route in which a request to the server occurs https://guides.emberjs.com/v2.4.0/routing/specifying-a-routes-model/

For instance:

export default Ember.Route.extend({
  model() {
    return this.store.findRecord('leader', 23);
  }
});

And from the server, most importantly, you should receive a response in the "json-api" style. Only in this case the response will be parsed as it should and will be sent to the store.

https://emberjs.com/api/data/classes/DS.JSONAPISerializer.html

https://jsonapi.org/format/

If your answer does not follow this format, then you need to implement your own adapter and serializer.

Scroll to Top