Невозможно прочитать свойство 'map' из undefined при просмотре массива без индекса - PullRequest
0 голосов
/ 19 марта 2019

Просто спасибо заранее за любую помощь и за огромный ресурс, которым это место было до сих пор.Я впервые задаю вопрос, и я все еще новичок, поэтому, пожалуйста, простите все очевидное, что я скучаю.

Я создал API из базы данных Postgresql, используя узел.Это нормально работает мой файл query.js ниже.

const Pool = require('pg').Pool
const pool = new Pool({
  user: 'user',
  host: 'localhost',
  database: 'database',
  password: 'password',
  port: 5432,
});

const tableThree = (request, response) => {
    pool.query('SELECT * FROM t3_0 ORDER BY time DESC LIMIT 10', (error, results) => {
      if (error) {
        throw error
      }
      response.status(200).json(results.rows)
    })
  }

  module.exports = {
    tableThree,
  }

Это передается в мой файл index.js ....

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const cors = require('cors');
const db = require('./queries')
const port = 3001

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

app.use(cors());

app.get('/', (request, response) => {
  response.json({ info: 'Node.js, Express, and Postgres API' })
});

app.get('/table3', db.tableThree);

app.listen(port, () => {
  console.log(`App running on port ${port}.`)
});

, который создает API, где я могу просматривать информацию из моей базы данных postgresql.

Из моего углового проекта я импортирую его как сервис ...

import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import { map } from 'rxjs/operators';



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


  constructor(private http: HttpClient) { 
    
  }

  tableThree() {
    return this.http.get("http://localhost:3001/table3")
      .pipe(map(result => result));
  }

}

Я обновил файл app.module.ts, чтобы можно было использовать службу ...

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { simulatorService } from './esim06.service';
import { HttpClientModule } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [simulatorService],
  bootstrap: [AppComponent]
})
export class AppModule { }

затем в файле app.components.ts я ввожу сервис и вижу ожидаемые данные.

import { Component } from '@angular/core';
import { simulatorService } from './esim06.service';
import { Chart } from 'chart.js';
import { map } from 'rxjs/operators/map';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  chart = [];
  
  constructor(private simulator: simulatorService) {}

  ngOnInit() {
    this.simulator.tableThree()
      .subscribe(res => {
        console.log(res)

        //let i13 = res['list'] || [].map(res => res.i13);
        //let alldates = res['list'] || [].map(res => res.i2)

        let i13 = res[''].map(res => res.i13);
        let alldates = res[''].map(res => res.i2)

        let dates = []
        alldates.forEach((res) => {
            let jsdate = new Date(res)
            dates.push(jsdate.toLocaleTimeString('en', { year: 'numeric', month: 'short', day: 'numeric' }))
        })
        console.log(dates)
        console.log(i13)

        this.chart = new Chart('canvas', {
          type: 'line',
          data: {
            labels: alldates,
            datasets: [
              {
                data: i13,
                borderColor: '#3cba9f',
                fill: false
              },
              //{
              //  data: acquireSun,
              //  borderColor: '#3cba9f',
              //  fill: false
              //},
            ]
          },
          options: {
            legend: {
              display: false
            },
            scales: {
              xAxes: [{
                display: true
              }],
              yAxes: [{
                display: true
              }]
            }
          }
        })
      });
  }

}

Для первого файла console.log (res) я могу просмотреть данные в инспекторе ....

(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {id: "4097", time: "2019-03-16T04:06:38.728Z", ple_id: "177550", meta_id: "1", reduced_id: null, …}
1: {id: "4094", time: "2019-03-16T04:06:31.710Z", ple_id: "177422", meta_id: "1", reduced_id: null, …}
2: {id: "4095", time: "2019-03-16T04:06:30.923Z", ple_id: "177404", meta_id: "1", reduced_id: null, …}
3: {id: "4096", time: "2019-03-16T04:06:28.333Z", ple_id: "177360", meta_id: "1", reduced_id: null, …}
4: {id: "4093", time: "2019-03-16T04:06:25.074Z", ple_id: "177292", meta_id: "1", reduced_id: null, …}
5: {id: "4090", time: "2019-03-16T04:06:22.743Z", ple_id: "177248", meta_id: "1", reduced_id: null, …}
6: {id: "4091", time: "2019-03-16T04:06:21.822Z", ple_id: "177230", meta_id: "1", reduced_id: null, …}
7: {id: "4092", time: "2019-03-16T04:06:19.356Z", ple_id: "177186", meta_id: "1", reduced_id: null, …}
8: {id: "4088", time: "2019-03-16T04:06:16.093Z", ple_id: "177118", meta_id: "1", reduced_id: null, …}
9: {id: "4089", time: "2019-03-16T04:06:13.648Z", ple_id: "177074", meta_id: "1", reduced_id: null, …}
length: 10

Тем не менее, когда я пытаюсь ссылаться на определенные части массива с помощью таких операторов, как ..

let i13 = res ['']. Map (res => res.i13);let alldates = res ['']. map (res => res.i2);

Я получаю следующую ошибку ..

core.js:14597 ERROR TypeError: Cannot read property 'map' of undefined
    at SafeSubscriber._next (app.component.ts:25)
    at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:194)
    at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next (Subscriber.js:132)
    at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next (Subscriber.js:76)
    at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:53)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:41)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:53)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:41)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:53)
    at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterSubscriber._next (filter.js:38)

Я считаю, что это происходит, потому что имя массива не определено.поэтому я не могу написать что-то вроде ..

let i13 = res ['list']. map (res => res.i13);

, но я не знаю, как заставитьпринять его как неопределенное или дать массиву индекс.Буду признателен за любую помощь в этом!

Спасибо!

1 Ответ

0 голосов
/ 19 марта 2019

Если вы выберете ответ на основе нашего обсуждения комментариев, вам будет проще объяснить, где ваша проблема.

В параметре 'res' возвращается массив. Массивы имеют доступ к методу map. Map принимает функцию и вызывает функцию один раз для каждого значения в массиве и в целом возвращает новый массив с возвращаемыми значениями map.

есть:

var res = [{ username: 'jsmith', firstname: 'John' }, { username: 'jdoe', firstname:' Jane" }];

var newArray = res.map(user => user.firstname);
console.log(newArray) // ['John', 'Jane']

На основе функции сопоставления первое имя будет выбрано из каждого объекта в массиве, и будет создан новый массив с этими значениями.

Массивы также доступны по целочисленному индексу. Итак:

var john = res[0];
console.log(john) // { username: 'jsmith', firstname: 'John' }

Так что в вашем случае вы можете просто сделать res.map, и вы получите каждое значение одно за другим, переданное этому обратному вызову, и вы сможете обработать их. Кроме того, вы можете получить доступ к элементам, например, по индексу res [0] .id.

вы не можете сделать res [0] .map, потому что объект, сохраненный в первой точке ответа, не является массивом

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...