Angular Google Chart - ERROR Error: Invalid row # 0 при попытке привязать данные к массиву данных MongoDB - PullRequest
0 голосов
/ 26 мая 2020

Я создаю диаграмму Sankey, которая будет получать данные из массива MongoDB, но когда я открываю ее, выдает ошибку.

ERROR Error: Invalid row #0
at Object.gvjs_ll [as arrayToDataTable]
at GoogleChartComponent.createDataTable
at SafeSubscriber._next
at SafeSubscriber.__tryOrUnsub
at SafeSubscriber.next 
at Subscriber._next 
at Subscriber.next 
at SwitchMapSubscriber.notifyNext
at InnerSubscriber._next 
at InnerSubscriber.next

Это первый раз, когда я использую Google Chart, поэтому я не конечно, почему у меня эта ошибка. Я пытаюсь немного осмотреться, но не нашел никакого решения, поэтому пришел сюда, чтобы спросить.

Я использую код для диаграммы из Здесь

firstchart.component.ts

import { Component, OnInit } from '@angular/core';
import {BackendService} from './../backend.service';

@Component({
  selector: 'firstchart',
  templateUrl: './firstchart.component.html',
  styleUrls: ['./firstchart.component.css']
})
export class FirstchartComponent implements OnInit {

  public data: object[];

  title = '';
  type = 'Sankey';

  columnNames = ['From', 'To', 'Weight'];
  options = {       
  };
  width = 1820;
  height = 740;

  constructor(private myservice: BackendService) {
  }

  ngOnInit() {
    this.myservice.GetList().subscribe(
      (res: any) => { 
        this.data = res["0"]["list"];
      },
      error => { 
      }
    );
  }

}

сервер. js

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const SLDBModel = require('./sldb_schema');         
require('./db');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.urlencoded({ extended: true }))

app.use(function (req, res, next)
{
    res.setHeader('Access-Control-Allow-Origin','*');
    res.setHeader('Access-Control-Allow-Methods','GET, POST, PUT, DELETE');
    res.setHeader('Access-Control-Allow-Headers','content-type, x-access-token');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

app.get('/api/getList', function (req, res)
{   
    SLDBModel.find({},function(err, data)
    {
        if(err)
        {
            res.send(err);
        }
        else
        {   
            res.send(data.map(v => v.toJSON()));
        }
    });
});

module.exports = app;

app.listen(3000, ()=>
{
    console.log("SERVER IS ONLINE! ON PORT 3000");
})

данные в MongoDB

{
    "_id" : ObjectId("5ec4672e44f01dcae82c3dde"),
    "num_rows" : 3,
    "list" : [ 
        {
            "From" : "All Population",
            "To" : "SBOBETH",
            "Weight" : 1,
            "S_NAME" : "SBOBETH",
            "S_ADD" : "sbobeth.com",
            "S_STATUS" : "UP",
            "S_DPV" : 565
        }, 
        {
            "From" : "All Population",
            "To" : "GTRCASINO",
            "Weight" : 1,
            "S_NAME" : "GTRCASINO",
            "S_ADD" : "gtrcasino.com",
            "S_STATUS" : "DOWN",
            "S_DPV" : 1680
        }, 
        {
            "From" : "All Population",
            "To" : "GTRBETCLUB",
            "Weight" : 1,
            "S_NAME" : "GTRBETCLUB",
            "S_ADD" : "gtrbetclub.com",
            "S_STATUS" : "UP",
            "S_DPV" : 4950
        }, 
        {
            "From" : "All Population",
            "To" : "77UP",
            "Weight" : 1,
            "S_NAME" : "77UP",
            "S_ADD" : "77up.bet",
            "S_STATUS" : "UP",
            "S_DPV" : 273
        }
    ]
}

HTML

<br>
<div style="text-align: center;">
   <google-chart #chart
      [title]="title"
      [type]="type"
      [data]="data"
      [columnNames]="columnNames"
      [options]="options"
      [width]="width"
      [height]="height">
   </google-chart>
</div>
<br>

1 Ответ

1 голос
/ 26 мая 2020

для данных, вы передаете массив объектов ...

[ 
    {
        "From" : "All Population",
        "To" : "SBOBETH",
        "Weight" : 1,
        "S_NAME" : "SBOBETH",
        "S_ADD" : "sbobeth.com",
        "S_STATUS" : "UP",
        "S_DPV" : 565
    }, 
    {
        "From" : "All Population",
        "To" : "GTRCASINO",
        "Weight" : 1,
        "S_NAME" : "GTRCASINO",
        "S_ADD" : "gtrcasino.com",
        "S_STATUS" : "DOWN",
        "S_DPV" : 1680
    }, 
    ...
]

, но диаграмма ожидает массив массивов ...

[ 
    ["All Population", "SBOBETH", 1],
    ["All Population", "GTRCASINO", 1],
    ...
]

попробуйте преобразовать данные следующим образом ...

ngOnInit() {
  this.myservice.GetList().subscribe(
    (res: any) => { 
      this.data = res[0].list.map(row => {
        return [row.From, row.To, row.Weight];
      });
    },
    error => { 
    }
  );
}
...