Ember中的计算属性基于异步数据

J B*_*J B 5 asynchronous ember.js

我正在尝试使用基于async,hasMany模型属性的值的计算属性,但无法在我的视图中显示它.

MyApp.Foo = DS.Model.extend({

    title: DS.attr('string'),
    peeps: DS.hasMany('peep', { async: true });

});

MyApp.Peep = DS.Model.extend({

    name: DS.attr('string'),
    email: DS.attr('string')

}); 

MyApp.Foo.FIXTURES = [

    { id: 1, title: 'nice', peeps: [1,2] }

];

MyApp.Peep.FIXTURES = [

    { id: 1, name: 'mypeep', email: 'peep@example.com' },
    { id: 2, name: 'mypeep2', email: 'peep2@example.com' }

];

MyApp.FooController = EmberObjectController.extend({

    showPeeps: function() {

        // This one works for this test data. 
        // return [{name: 'baz', email: 'bar'}];

        var peepList = this.get('content.peeps.[]').then(function(c) {

            // This one does not work, even for this test data.
            return {name: 'baz', email: 'bar'}];

        });

    }.property('content.peeps.[]');

});
Run Code Online (Sandbox Code Playgroud)

在我看来,有些东西:

{#each peep in controller.showPeeps}}{{peep.name}}{{/each}}
Run Code Online (Sandbox Code Playgroud)

我可以使用console.log()查看"then()"中的所有数据,并且正如它在代码注释中所指出的那样,如果我从"then()"中获取返回值,那么它可以工作 - 但是然后是实际数据是空的,因为它作为异步返回.如果我试图让它非同步,我得到

未捕获的TypeError:无法调用未定义的方法'resolve'

我尝试了很多计算属性代码的变体(使用@each,使用model.peeps - 所有这些都正确地显示了console.log()中的数据,但是在视图中没有.在视图中,它始终是未定义的,除非我只是在then()之外返回虚拟数据 - 正确显示

我错过了什么?

GJK*_*GJK 8

不要将hasMany关系视为promise,将其视为数组.这就是重点DS.PromiseArray.如果您只是想要用户,甚至不需要使用计算属性,只需peeps在模板中使用即可.但是,如果您需要以某种方式转换数据,请使用map.

showPeeps: function() {
    return this.get('peeps').map(function(peep) {
        return { name: peep.name, email: peep.email };
    });
}.property('peeps.@each')
Run Code Online (Sandbox Code Playgroud)

此外,不要看[]房产.只有在从阵列中添加或删除项目时才会更新.您的数组内容不会更改,内容的内容也在变化.你应该看看这家@each酒店.您也不需要添加[]到属性名称的末尾,也不需要为属性添加前缀content..