如何使用promise对象绑定聚合物模板dom-repeat?

时间:2018-02-13 16:47:53

标签: javascript promise polymer-1.0 polymer-2.x

我试图使用函数绑定下拉值,这个调用firestore然后我使用promise返回值

HTML

<template is="dom-repeat" items="{{_modOptsArry(item.modKey)}}" as="opt">
     <paper-item value="{{opt.$key}}">{{opt.obj.val}}</paper-item>
</template>

的JavaScript

_modOptsArry(modeKey) { 
    let opts = [];
    var promise = new Promise((resolve, reject) => {
        firebase.firestore().collection("record").doc("s1").collection("class").orderBy('o').onSnapshot(function (querySnapshot) {
            // let opts = [];
            querySnapshot.forEach(function (doc) { 
                var model = doc.data(); 
                opts.push({ $key: doc.id, obj: { val: model.nm } });
            });
            resolve(opts); 
        })
    })
    promise.then(function (result) {
        return Promise.resolve(result); // Here i am returning array but in the dom-repeat it not binding values because it is returning Promise Object My Array is there inside this Promise object. how to resolve this problem..
    }); 
}

2 个答案:

答案 0 :(得分:0)

有一个看起来像这样的功能

getDropdownItems(props, item) {
    if (!this.props[item])
        this._modOptsArry(item);
    return this.props[item]
}

让您的_mopOptsArry方法将结果分配给this.props[item];然后通知对象。像这样:

this.props[item] = yourResultArray;
this.notifyPath('props.' + item);

拥有一个名为props的属性,其值为{}

然后在你的HTML中,而不是调用this._modOptsArry;致电[[getDropdownItems(props.*, item.modkey)]]

答案 1 :(得分:0)

像这样改变你的方法:

_modOptsArry() { 
    let opts = []
    const that = this
    firebase.firestore().collection("record").doc("s1").collection("class").orderBy('o').onSnapshot(function (querySnapshot) {
        querySnapshot.forEach(function (doc) { 
            var model = doc.data()
            opts.push({ $key: doc.id, obj: { val: model.nm } })
        })
        that.set('myArray', opts)
    })
}

将myArray绑定到dom-repeat模板

<template is="dom-repeat" items="{{myArray}}" as="opt">
     <paper-item value="{{opt.$key}}">{{opt.obj.val}}</paper-item>
</template>