1

我从服务器获取下一个 JSON:

{
    "contextPath":"http://apps.dhis2.org/demo",
    "user":{
        "id":"GOLswS44mh8",
        "name":"System Administrator",
        "isAdmin":true,
        "ou":{
             "id":"ImspTQPwCqd",
             "name":"Sierra Leone"
        }
     }
}

我需要将此 JSON 转换为两个模型:用户模型和组织单元模型。

我阅读了本教程http://docs.sencha.com/touch/2.2.1/#!/api/Ext.data.reader.Reader所以它是我的代码:

用户型号:

Ext.define('mobile-visualizer.model.User', {
    extend: 'Ext.data.Model',

    config: {
        fields: [
            {name: 'id',  type: 'string'},
            {name: 'name',   type: 'string'},
            {name: 'isAdmin', type: 'boolean'}
        ],
        hasOne: {
            model: "mobile-visualizer.model.OrganizationUnit",
            name: "ou"
        },
        proxy: {
            type: 'ajax',
            url : 'http://apps.dhis2.org/demo/dhis-web-visualizer/initialize.action',
            method : 'GET',
            withCredentials : true,
            useDefaultXhrHeader : false,
            reader: {
                type: 'json',
                rootProperty: 'user'
            }
        }
    }
});

组织单元模型:

Ext.define('mobile-visualizer.model.OrganizationUnit', {
    extend: 'Ext.data.Model',

    config: {
        fields: [
            {name: 'id',  type: 'string'},
            {name: 'name',   type: 'string'}
        ],
        belongsTo: 'mobile-visualizer.model.User'
    }
});

商店

Ext.define('mobile-visualizer.store.UsersStore', {
    extend : 'Ext.data.Store',
    model : "mobile-visualizer.model.User",
    autoLoad : false,
    storeId : "usersStore",

    proxy : {
        type : 'ajax',
        url : 'http://apps.dhis2.org/demo/dhis-web-visualizer/initialize.action',
        method : 'GET',
        withCredentials : true,
        useDefaultXhrHeader : false,
        reader : {
            type : 'json',
            rootProperty : 'user'
        }
    }
});

因此,当我尝试使用另一个代码从商店获取用户时:

        var store = Ext.create('mobile-visualizer.store.UsersStore');
        store.load({
                    callback : function() {
                        // the user that was loaded
                        var user = store.first();
                        console.log(user.ou())
                    }
                });

我有错误:未捕获的 TypeError: Object [object Object] has no method 'ou'

可以获取有关 user 的所有信息,但无法从user获取ou。它看起来像一些关联问题。

但我做的一切都像官方教程一样。请帮助解决这个问题。谢谢。

4

1 回答 1

1

Follow my rules and everything will come out rosy:

http://extjs-tutorials.blogspot.ca/2012/05/extjs-hasmany-relationships-rules.html

http://extjs-tutorials.blogspot.ca/2012/05/extjs-belongsto-association-rules.html

These are for extjs, but very similar for sencha touch.

You are forgetting the associationKey.

Also, no need to redefine proxy in store as it will inherit its model's proxy.

Also, a user probably belongs to an org unit and doesn't have one...

于 2013-06-26T21:02:48.323 回答