简体   繁体   中英

Ember-data cannot read property 'length' of undefined

I'm trying to get data from api server with ember-data ,i added ember-data to ember starter-kit.

Getting with

App = Ember.Application.create();

App.Router.map(function() {
  // put your routes here
});

App.ApplicationAdapter = DS.RESTAdapter.extend({
    namespace: 'emberjs/ember.js',
    host     : 'https://api.github.com/repos'
});

App.Store = DS.Store.extend({
    adapter: 'App.ApplicationAdapter'
});

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('pull');
  }
});

App.Pull = DS.Model.extend({
    url : DS.attr(),
    title  : DS.attr(),
    body  : DS.attr()
});

Giving the same error for every request. then i try with github, it gives the same error.

Api that i connected: Github api

Error while processing route: index Cannot read property 'length' of undefined TypeError: Cannot read property 'length' of undefined

Ember expects a pluralised root object when returning multiple results, in this case pulls , ie

{
    "pulls": [...]
}

As you're working with an api you don't control you'll need to change the data into embers expected format with a modified Serializer like so:

/app/serializers/pull.js

import DS from "ember-data";

export default DS.RESTSerializer.extend({
    normalizePayload: function(payload) {
        if(Array.isArray(payload)) {
            return {"pulls": payload };
        }
        return payload;
    }
});

Information on serializer: http://emberjs.com/api/data/classes/DS.RESTSerializer.html

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