async:true仍然需要Ember中的关联模型

时间:2014-09-29 07:49:07

标签: ember.js ember-data

我有两个使用ember-data的模型:

App.Post = DS.Model.extend({
    'comments': DS.hasMany('comment', {async: true})
});

App.Comment = DS.Model.extend({
    postId: DS.belongsTo('post', {async: true})
});

当我尝试通过路线获取帖子时

model: function(params) {
    return this.store.find('post', params.query);
}

虽然“async”设置为true,但是Ember会尝试查找注释,这些注释不是API的帖子响应的一部分。

Cannot read property 'comments' of undefined

更新

一些更详细的信息,补充上述信息:

window.App = Ember.Application.create();
App.ApplicationAdapter = DS.RESTAdapter.extend({
    host: 'http://api.example.com'
});

App.ApplicationController = Ember.Controller.extend({
    actions: {
        search: function() {
            var term = this.get('query');
            this.transitionToRoute('post', { query: term });
        },
        reset: function() {
            clearTimeout(this.get("timeout"));
            this.setProperties({
                isProcessing: false,
                isSlowConnection: false
            });
        }
    }
});

App.Router.map(function() {
    this.resource('post', { path:'/:query' }, function(){
        this.route('create');
        this.route('edit');
    });
});

App.PostRoute = Ember.Route.extend({
    model: function(params) {
        return this.store.find('post', params.query);
    }
});

数据

"posts": [
    {
        "id": 1,
        "title": "Lorem ipsum",
        "comments": ["1", "2"],
    },
    {
        "id": 2,
        "title": "dolor sit amet",
        "comments": ["1", "2"],
    }
]

"comments": [
    {
        "id": "1",
        "body": "comment content 1",
        "postId": 1
    },
    {
        "id": "2",
        "body": "comment content 2",
        "postId": 1
    }
]

2 个答案:

答案 0 :(得分:0)

如果您想获得已经在商店中加载的信息,您需要使用

this.store.all('post')

然后使用过滤器获取您想要的信息作为示例

this.store.all('post').filterBy('key', value)

如果需要,请查看文档以获取有关过滤的更多信息 http://emberjs.com/guides/enumerables/

答案 1 :(得分:0)

正如ShinySides的评论中所述,Ember期望一个对象,而不是数组,因为路由:如果你有路由/帖子,响应的JSON必须是一个包含所有帖子的数组:

"posts": [
    {
        "id": 1,
        "title": "Lorem ipsum",
        "comments": ["1", "2"],
    },
]

但对于路线/帖子/搜索任何内容,Ember期望一个对象,只代表一个帖子:

"post": {
    "id": 1,
    "title": "Lorem ipsum",
    "comments": ["1", "2"],
},

我的问题的解决方案:QUERYING FOR RECORDS

var posts = this.store.find('posts', { term: "search for whatever in posts" });

添加参数" term"到API请求(例如api.example.com/posts?term=whatever)。 Ember现在将返回一个数组。