简体   繁体   中英

How to map json data coming from an REST-API to ember.js model?

I'm new to EmberJS and try to connect my EmberJS-frontend to an API via the RESTAdapter. I'm using ember-1.0.0-rc.6 and ember-data-latest (Version: v0.13-59-ge999edb). From the API I get the following JSON code:

{
    "page": 1,
    "limit": 5,
    "total": 4,
    "results": [
        {
            "id": 1,
            "title": "something3",
            "description": "asd3"
        },
        {
            "id": 2,
            "title": "something3",
            "description": "asd3"
        },
        {
            "id": 3,
            "title": "something2",
            "description": "asd2"
        },
        {
            "id": 4,
            "title": "something",
            "description": "asd"
        }
    ]
}

My RESTAdapter looks like the following:

App.Store = DS.Store.extend({
    revision: 13,
    adapter: DS.RESTAdapter.extend({
        url:"http://localhost/api/app_dev.php"
    })
});

My model looks like this at the moment:

App.Modelname = DS.Model.extend({
    title: DS.attr('string')
});

With this I get the following error in the browser console:

Assertion failed: Your server returned a hash with the key page but you have no mapping for it

MY question is how to connect the json output from the api to my ember model without changing the api on the server?

Thanks in advance for your support !

If your model is like this:

App.Modelname = DS.Model.extend({
  title: DS.attr('string')
});

Then the RESTAdapter expects a JSON format like this:

{
  "modelNames": [
    {
        "id": 1,
        "title": "something3",
        "description": "asd3"
    },
    {
        "id": 2,
        "title": "something3",
        "description": "asd3"
    },
    {
        "id": 3,
        "title": "something2",
        "description": "asd2"
    },
    {
        "id": 4,
        "title": "something",
        "description": "asd"
    }
  ]
}

You can of course tweak some of this behavior by configuring some aspects of the JSONSerializer and the RESTAdapter , IMO to have full control I would suggest to create your own adapter by overriding the vital functions like find , findAll etc. and go with plain $.ajax(...) . Otherwise you would need to make your backend obey the JSON format ember-data expects.

Hope it helps, at least to take a decision.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM