错误TypeError:无法读取未定义的属性“数据”

时间:2020-05-20 17:00:09

标签: angular mongodb

我是angular和mongodb的新手。我正在尝试从MongoDB中提取数据并将其显示在Angular Material Table中。 但是我遇到了错误

“ ERROR TypeError:无法读取未定义的属性'data'”

当我尝试打开应用程序时,MongoDB中的数据将不会加载。 我设法缩小了与此行有关的问题。

return this.myservice.GetList().subscribe(res => this.dataSource.data = res["0"]["data"]);
                                                                                ^^^^^^^^

谢谢!

tabledata.component.ts

import {BackendService} from './../backend.service';
import {Component, OnInit, ViewChild} from '@angular/core';
import {MatPaginator} from '@angular/material/paginator';
import {MatSort} from '@angular/material/sort';
import {MatTableDataSource} from '@angular/material/table';


@Component({
  selector: 'tabledata',
  templateUrl: './tabledata.component.html',
  styleUrls: ['./tabledata.component.css']
})

export class TabledataComponent implements OnInit {
  displayedColumns = ['S_NAME', 'S_ADD', 'S_STATUS'];
  dataSource = new MatTableDataSource();

  @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
  @ViewChild(MatSort, {static: true}) sort: MatSort;

  constructor(private myservice: BackendService) {
  }



  ngOnInit() {

    return this.myservice.GetList().subscribe(res => this.dataSource.data = res["0"]["data"]);

  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();

    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }
}

网站列表集合中的MongoDB数据

{
    "_id" : ObjectId("5ec4672e44f01dcae82c3dde"),
    "error" : "0",
    "num_rows" : 3,
    "data" : [ 
        {
            "S_NAME" : "SBOBETH",
            "S_ADD" : "sbobeth.com",
            "S_STATUS" : "UP"
        }, 
        {
            "S_NAME" : "GTRCASINO",
            "S_ADD" : "gtrcasino.com",
            "S_STATUS" : "DOWN"
        }, 
        {
            "S_NAME" : "SBOBETH",
            "S_ADD" : "sbobeth.com",
            "S_STATUS" : "DOWN"
        }, 
        {
            "S_NAME" : "GTRBETCLUB",
            "S_ADD" : "gtrbetclub.com",
            "S_STATUS" : "UP"
        }, 
        {
            "S_NAME" : "77UP",
            "S_ADD" : "77up.bet.com",
            "S_STATUS" : "UP"
        }, 
        {
            "S_NAME" : "DATABET88",
            "S_ADD" : "databet88.net",
            "S_STATUS" : "DOWN"
        }, 
        {
            "S_NAME" : "FAFA855",
            "S_ADD" : "fafa855.com",
            "S_STATUS" : "UP"
        }
    ]
}

backend.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse, HttpHeaders, HttpRequest  } from "@angular/common/http";
import { catchError, map, tap,  } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class BackendService {

  constructor(private _http: HttpClient) { }

  GetList() 
  {

    return this._http.get('http://localhost:3000/api/getList')

  }

  private handleError<T>(operation = 'operation', result?: T)
  {
    console.log("error");
    return null;
  }

  private log(message: string)
  {
    console.log("log");
  }

}

server.js

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

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

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

我尝试过console.log(res);从评论中的建议开始,先检查我的“ res”数据。

enter image description here

并且从server.js我尝试了console.log(data);

enter image description here

他们两个都返回[]不确定这是什么意思 关于如何修复有什么建议吗?

3 个答案:

答案 0 :(得分:1)

ngOnInit()内部替换

return this.myservice.GetList().subscribe(res => this.dataSource.data = res["0"]["data"]);

this.myservice.GetList().subscribe(res => {
        console.log(res); // Check your 'res' data first
        dataSource.data = res["0"]["data"];
    });

注意:请控制台您的 res 来了解您的响应数据。

答案 1 :(得分:0)

似乎data属性是对象的父级。在ngOnInit()

中尝试以下操作
ngOnInit() {
  this.myservice.GetList().subscribe(
    res => { 
      this.dataSource.data = res['data'];
    },
    error => { 
      // always good practice to handle error in HTTP observables
    }
  );
}

答案 2 :(得分:0)

也尝试在服务器端将数据转换为Json

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

也请尝试console.log(data)。如果它是数组,请用res.send(data)替换res.send(data.map(v => v.toJSON())