Таблица Angular 2 (ng2-smart-table) — получить ВСЕ данные из JSON (для каждого уровня json)

Сначала я публикую свой код

сервис.тс

import { Component, NgModule, OnInit, ViewChild, Directive, EventEmitter, Output, ElementRef } from '@angular/core';
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'


@Component({
 styles: [],
 template: ""
})
export class PageService {


constructor(private http: Http) {}


    getAllPage() {
            //noinspection TypeScriptUnresolvedFunction
            return this.http.get(window.location.origin + "/app/json/profile.json").map(res => res.json());
    }
}

tablecomponent.ts

import { Component, NgModule, OnInit, ViewChild, Directive, EventEmitter, Output, ElementRef } from '@angular/core';
import { Ng2SmartTableModule, LocalDataSource } from 'ng2-smart-table';
import {Http} from '@angular/http';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
import { DomSanitizer, SafeResourceUrl, SafeUrl, BrowserModule } from '@angular/platform-browser';
import ButtonProductRenderComponent from './button-product-render.component';
import * as _ from 'underscore';
import { PageService } from '../order-request';

@Component({
 styles: [],
 templateUrl: '../../templates/table/profile-table.html',
})
export class ProfileTableComponent implements OnInit{
    rows;
    datas;
    profilojson;
    source: LocalDataSource; // add a property to the component
    settings = {
        mode: 'external',
        add: {
            addButtonContent: "<i class='icon-plus'></i>",
            createButtonContent: "Conferma",
            cancelButtonContent: "Annulla"
        },
        delete: {
            deleteButtonContent: "Cancella"
        },
        edit: {
            editButtonContent: "<i class='icon-copy2'></i>"
        },
        sort: {
            sortDirection: true
        },
        actions: false,
        noDataMessage: "Nessun risultato trovato",
        columns: {
            groupID: {
                title: 'Group Id',
                filter: false,
                class: "colonneTabella",
                width: "15%"
            },
            groupName: {
                title: 'Group Name',
                filter: false,
                class: "colonneTabella",
                width: "15%"
            },
            groupDescr: {
                title: 'Group Description',
                filter: false,
                class: "colonneTabella",
                width: "25%"
            },
            functionList: {
                title: 'Function List',
                filter: false,
                class: "colonneTabella",
                width: "20%"}
            ,
            button: {
                title: 'Buttons',
                filter: false,
                class: "colonneTabella",
                type: 'custom',
                renderComponent: ButtonProductRenderComponent,
            }
        }
    };


        /*{
            groupID: this.datas.groupID,
            groupName: "QD4",
            groupDescr: "Amministratore",
            functionList: "C312D5"

        }*/
pages: LocalDataSource;  

constructor(private pageService:PageService) {
        this.pages = new LocalDataSource();

        pageService.getAllPage().toPromise().then(data => {
            this.pages.load(data); 
            //console.log(this.pages.find("id")); 
            this.pages.reset();
        });
    }       



/*
        let profileInput; 
        this.http.get('app/json/profileInput.json')
        .subscribe(res =>{
            profileInput = res.json()
            //console.log(JSON.stringify(profileInput));
            this.profileConstructor(profileInput.rows);
            }
        );*/




    profileConstructor(profileRows){
       /*console.log(JSON.stringify(
                _.object(JSON.stringify([_.object([profileRows], ['riga'])], [1, 2, 3, 4, 5]))
            )
       );*/
        /*function group(array) {
            var map = new Map;

            array.forEach(function (o) {
                var group = map.get(o[0]) || { groupID: o[0], groupName: o[1], groupDescr: o[3], functionList: [] };
                if (!map.has(o[0])) {
                    map.set(o[0], group);
                }

               // var evens = _.filter(o, function(item){ return item[0] == o[0]});
               array.forEach(function( o=2 ) {
                    group.functionList = [{
                        'id': o[2], 'value': o[4]
                    }];
               })
                //console.log(evens)
            });
            return [...map.values()];
        }

        var rows = profileRows,
            result = group(rows);

        console.log(JSON.stringify(result));*/

      /* var arr = profileRows.reduce((a, b) => {
  let flag = false,
    obj = {};
  a.forEach(item => {
    if (item.groupID === b[0] && item.groupName === b[1] && item.groupDescr === b[3]) {
      item.functionList= {'id': b[2], 'value': b[4]}
      flag = true;
    }
  });
  if (!flag) {
    obj[b[2]] = b[4];
    a.push({
      "groupID": b[0],
      "groupName": b[1],
      "groupDescr": b[3],
      "functionList": [][b[2]]
    });
  }
  return a;
}, []);

console.log(JSON.stringify(arr));*/
    } ;



   ngOnInit() {

  }

    onCreate(event: any) {
        console.log("ciao");
    }
    onEdit(modal){
        console.log('AAAAAAAAAAA');
        modal.open();
    }

}

И шаблон таблицы

<div class="col-md-6 col-lg-6 pull-left"><div class="pull-left filter-search"><input #search class="search" type="text" [ngModel]="mymodel" placeholder="Cerca" (ngModelChange)="onSearch(search.value)" ></div></div>
     <div class="col-md-6 col-lg-6 pull-right"><div class="pull-right filter-external"> <i class="icon-circle-plus pull-left" [routerLink]="['/aggiungi-gruppo']"></i><i class="icon-circle-right pull-right"></i></div></div>
    <ng2-smart-table [settings]="settings" [source]="pages" (custom)="modal.open()"></ng2-smart-table>   

JSON:

[  
   {  
      "groupID":1,
      "groupName":"GESTORE_PRATICHE",
      "groupDescr":"GESTORE PRATICHE",
      "functionList":[
         {  
            "id":1,
            "value":"canViewFolderManagement"
         }
         ] 

   },
   {  
      "groupID":2,
      "groupName":"ADM",
      "groupDescr":"AMMINISTRATORE",
      "functionList":[
         {  
            "id":1,
            "value":"canViewFolderManagement"
         },
         {  
            "id":2,
            "value":"canViewAdministrationManagement"
         },
         {  
            "id":3,
            "value":"canViewConventions"
         },
         {  
            "id":4,
            "value":"canViewProfiles"
         },
         {  
            "id":5,
            "value":"canManageProfiles"
         }
      ]
   },
   {  
      "groupID":3,
      "groupName":"BOM",
      "groupDescr":"OPERATORE DI BACK OFFICE",
      "functionList":[  
         {  
            "id":1,
            "value":"canViewFolderManagement"
         },
         {  
            "id":2,
            "value":"canViewAdministrationManagement"
         }
      ]
   }
]

В итоге имею следующий результат:

введите здесь описание изображения

Как я могу увидеть данные в столбце functionList? мой код работает неправильно, он просто сохраняет данные json первого уровня. Спасибо


person Jamil89    schedule 17.07.2017    source источник
comment
вы можете использовать функцию подготовки значения для каждой функции, чтобы получить вложенные данные   -  person Karan Garg    schedule 17.07.2017
comment
спасибо... я пробовал с valuePrepareFunction: (value) =› {return JSON.stringify(value)}, и, кажется, работает (partial... я просто вижу данные как массив, на данный момент :))   -  person Jamil89    schedule 17.07.2017
comment
лучшим подходом было бы изменить данные (создать новый массив объектов только тех данных, которые вам нужны) после получения json с сервера, а не подавать его непосредственно в таблицу. Таким образом, вам не нужно использовать функцию valueprepare каждый раз   -  person Karan Garg    schedule 17.07.2017
comment
Проблема в том, что данные должны возвращаться таким образом, я не могу изменить структуру atm :(   -  person Jamil89    schedule 17.07.2017
comment
вам не нужно менять структуру на стороне сервера. Вы можете изменить ее на стороне клиента. Потому что, если вы используете подготовку значения, то даже сортировка не будет работать простым способом. Прежде чем делать это, просто измените свои данные this.pages.load( данные);   -  person Karan Garg    schedule 17.07.2017


Ответы (2)


Я исправил эту ошибку, используя valuePrepareFunction: (cell,row).

вы можете использовать код ниже в настройках столбца

functionList: {
    title: 'Function List',
    type:'html',
    valuePrepareFunction: (cell,row) => {
        var valueModelList = JSON.parse(row.functionList);
        var htmlEntity ="";
        valueModelList.foreach(valueModel=>{
            htmlEntity += valueModel.id+ " : " + valueModel.value + '<br>';
        })
        return htmlEntity;
    }
}

надеюсь это работает

person Muhammed Çağrı Elverişli    schedule 27.09.2017
comment
Спасибо valuePrepareFunction: (cell,row) => row дает целое для доступа к вложенным объектам - person Sarvesh Acharya; 13.09.2019

У вас есть 2 варианта: использование пользовательских компонентов рендеринга или сопоставление значения строки для столбца. В случае, если это просто встроенные значения, для меня предпочтительнее 2-й. См. образец: categoryLabel и categoryName:

settings = {
    add: {
        addButtonContent: '<i class="nb-plus"></i>',
        createButtonContent: '<i class="nb-checkmark"></i>',
        cancelButtonContent: '<i class="nb-close"></i>',
    },
    edit: {
        editButtonContent: '<i class="nb-edit"></i>',
        saveButtonContent: '<i class="nb-checkmark"></i>',
        cancelButtonContent: '<i class="nb-close"></i>',
    },
    delete: {
        deleteButtonContent: '<i class="nb-trash"></i>',
        confirmDelete: true,
    },
    columns: {
        categoryLabel: {
            title: 'Category Label',
            valuePrepareFunction: (cell, row) => row.category.label,
        },
        categoryName: {
            title: 'Category Name',
            valuePrepareFunction: (cell, row) => row.category.name,
        },
        likes: {
            title: 'Likes Amount',
        },
person Alex Efimov    schedule 26.01.2021