【问题标题】:How to read data from json instead of array using ng2-dnd package?如何使用 ng2-dnd 包从 json 而不是数组中读取数据?
【发布时间】:2016-07-16 21:50:58
【问题描述】:

我使用 ng2-dnd 包,简单的 html5 包在列表上进行拖放以对其进行排序。

我只能弄清楚如何从数组中填充列表,而我需要它来自 JSON。

这是我的代码:

import { Component } from '@angular/core';

import { DND_DIRECTIVES } from 'ng2-dnd/ng2-dnd';

import { Report } from "./Report";

@Component({
    selector: 'my-app',
    styleUrls: ['style.css'],
    directives: [DND_DIRECTIVES],
    template: `
    <h1 align="center">{{title}}</h1>
    <h2>list of reports:</h2>
    <div dnd-sortable-container [sortableData]="reports">
    <div *ngFor="let rep of reports; let i=index" dnd-sortable [sortableIndex]="i">
    ID:{{rep.id}} <p></p> Name:{{rep.name}}
    </div>
    <div>{{reports | json}}</div>
    `
})

export class AppComponent {

    title = 'Reorder List';

    reports = [
        new Report(1, 'Italy'),
        new Report(2, 'Spain'),
        new Report(3, 'Italy'),
        new Report(4, 'Spain'),
        new Report(5, 'Netherlands'),
        new Report(6, 'Italy')
    ];
}

如果有人知道我如何使用它从报告的 JSON 中获取数据,而不是从报告数组中获取数据,那真的会对我有所帮助:)

谢谢!!

【问题讨论】:

    标签: angularjs json angularjs-directive angular


    【解决方案1】:

    假设您返回的数据是一个 JSON 数组,您可以使用 map 函数返回一个 Report` 数组,如下所示:

    var data = [{id: 1 , name:"Italy"}, {id: 2 , name:"Viet Nam"}];
    var reports =     data.map(x=> new Report(x.id, x.name));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 2021-06-14
      • 2019-03-07
      • 2020-07-18
      • 1970-01-01
      • 2018-10-03
      相关资源
      最近更新 更多