json - Table Angular 2 (ng2-smart-table) - 从 JSON 获取所有数据(对于 json 的每个级别)

标签 json angular typescript ng2-smart-table

首先我发布我的代码

服务.ts

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());
    }
}

表组件.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"
         }
      ]
   }
]

最后我得到以下结果:

enter image description here

如何查看functionList列中的数据?我的代码无法正常工作,它只保留第一级 json 数据。谢谢

最佳答案

我已使用 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;
    }
}

希望能成功

关于json - Table Angular 2 (ng2-smart-table) - 从 JSON 获取所有数据(对于 json 的每个级别),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45146432/

相关文章:

c# - Atata selenium 网络驱动程序无法在 Angular 应用程序上通过 id 找到控件

angular - 按钮单击打开组件

typescript - 如何发出显示/隐藏加载程序覆盖?

javascript - 来自 javascript 的 fetch 调用无法访问 java REST 服务

angular - mat-expansion-panel 主体不适用于 ngFor

javascript - ASP.NET Core 2.0 Razor + Angular 4 混合

reactjs - ionic react : How to properly type (typescript) event object parameter in delegated anonymous onIonChange event handler

java - 如何使用 Retrofit 查询某些 JSON 项?

java - 在Java中将多维JSON数组解析为平面int列表

javascript - 如何解析此 XSL 文件并读取将其嵌入 HTML 文件中的元素