首页 > 解决方案 > ExtJS:如何在 initComponent 方法中等待 Promise 响应?

问题描述

我已经实现了一种initComponent方法来分类并通过方法Container加载配置。itemsPromise

期间的事情debugging首先进入callParent线路,然后执行进入Promise方法。我必须重新加载浏览器才能获取Promise响应。

我已经尝试过then()方法initComponent但给出了错误。我怎样才能达到这种用法?

- 容器类initComponent

Ext.define('MyApp.view.Bar', {
    extend: 'Ext.container.Container',
    xtype: 'barview',
    requires: [],
    controller: 'barctrl',
    viewModel: {
        type: 'barvm'
    },

    initComponent: function () {
        let me = this;
        let fooInfo = MyApp.FooInfoClass.getFooInfo(); //There is a debugger in FooInfoClass but miss this one

        if (fooInfo) {
            if (fooInfo.self) {
                me.items = [
                    {
                        xtype: 'componentA'
                    }
                ];
            } else if (fooInfo.reference) {
                me.items = [
                    {
                        xtype: 'componentB'
                    }
                ];
            } else {
                me.items = [
                    {
                        xtype: 'componentC'
                    }
                ];
            }
        }

        debugger //Firstly comes to this one then goes to Promise 
        me.callParent(arguments);
    }
});

- Promise 类和方法;

Ext.define('MyApp.FooInfoClass', {
    requires: [],
    singleton: true,
    endpoint: MyApp.Url(),

    getFooInfo: function () {
        let me = this;
        let responseInfo = localStorage.getItem('foo-info');

        return JSON.parse(responseInfo);
    },

    setFooInfo: function (foo) {
        let me = this;

        me.foo = JSON.stringify(foo);
        localStorage.setItem(me.fooInfo, me.foo);
    },

    fooInfo: function () {
        let me = this;

        return new Ext.Promise(function (resolve, reject) {
            Ext.Ajax.request({
                url: me.endpoint + '/info',

                success: function(response, opts) {
                    let obj = Ext.decode(response.responseText);
                    let data = obj.data[0];
                    debugger //Secondly comes to here!
                    me.foo = data;
                    me.setFooInfo(me.foo);
                    resolve(me.foo);
                },

                failure: function(response, opts) {
                    console.log('server-side failure with status code ' + response);
                    reject(response);
                }
            });
        });
    }
});

标签: javascriptextjspromisecontainersresponse

解决方案


在获得所需数据之前,您不应推迟完成该initComponent功能。您可以先获取数据并在所有需要的信息一起实例化组件(执行Ext.create()inside Promise.then()),或者让组件获取所需的信息并在运行时根据这些信息添加子组件。在致电之前,您真正必须callParent知道的事情很少initComponent

如果我是你,而不是使用me.items =,我只会使用me.add()以便在初始化之后在运行时添加子组件。

我为你做了一个简单的小提琴:https ://fiddle.sencha.com/#view/editor&fiddle/2k9r


推荐阅读