简体   繁体   English

无法绑定来自本地json的数据以查看聚合物2

[英]Not able to bind data from local json to view polymer 2

I am using Polymer 2 and want to bind data from a local json file. 我正在使用Polymer 2,并希望绑定本地json文件中的数据。 But each time I tried it it is not able to fetch the json file only. 但是每次我尝试它都无法仅获取json文件。

There are 2 ways I have tried to achieve it with: 我尝试了2种方法来实现它:

1) USING 1)使用

<iron-ajax url="data/employees.json" handle-as="json" last-response="{{items}}" auto>
</iron-ajax>

Folder Structure: 资料夹结构:

文件夹结构

<iron-list items="{{items}}" as="item">
    <template>
        <div class="item">
            <b>[[item.nickname]]</b>
            <p>[[item.phone]]</p>
        </div>
    </template>
</iron-list> 

I have also imported both iron-ajax and iron-list 我还同时导入了“ ajax”和“ list”

2) USE $.get to extract data fron json in start and put it in a variable to bind it to view. 2)使用$.get在开始时从json中提取数据,并将其放在变量中以将其绑定到视图。

<script>
    class IronListClass extends Polymer.Element {
        static get is() {return 'iron-comp'}

        ready() {
            super.ready();
            var that = this;
            // $.get('data/employees.json', function(data) {
            //     that.employees = $.parseJSON(data).results;
            //     console.log(that.employees);
            // });
            $.get('data/employees.json', function(data) {
            this.employees = $.parseJSON(data).results;
            console.log(this.employees);
            }.bind(this));
        }        
    }
    window.customElements.define(IronListClass.is, IronListClass);
</script>

tried with that = this also. 尝试与=也。

You may load the json file as follow example as its working at my app already. 您可以按照以下示例加载json文件,因为它已在我的应用程序中正常工作。

   <iron-ajax 
            auto 
            url$="{{url}}" 
            handle-as="json" 
            last-response="{{loadedItems}}"
           >
    </iron-ajax>

... ...

     static get properties() { return { 
        url :{
            type:String,
            value() {return "./data/employees.json"; }
        }

... ...

    static get observers() { return ['checkJsonFileLoaded(loadedItems)']}

    checkJsonFileLoaded(j) {
       if (j) {
           this.set('items', j);
           console.log(items); //u should see the loaded json file. If so than the problem is iron-list (to publish the result)
       }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM