错误TypeError:无法读取Angular中未定义的属性'forEach'

时间:2020-07-14 14:08:59

标签: javascript angular highcharts

我尝试使用Angular和API制作一个highchart应用程序,但我不知道为什么会收到此错误:ERROR TypeError:无法读取DashboardComponent.GetProfitLossChart(47)中未定义的属性'forEach'。我没有我的代码中有任何错误,但我在Google Chrome浏览器页面中收到此错误。

这是我的DashboardComponent.ts。

import { Component, OnInit } from '@angular/core';
import {Stockmodel} from '../model/stockmodel';
import { StockService } from '../services/stock.service';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import * as Highcharts from 'highcharts';
import { debug } from 'util';

@Component({
 selector: 'app-dashboard',
 templateUrl: './dashboard.component.html',
 styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
 addForm: FormGroup;
 url: string = 'http://localhost:44311/api/GetStockData';
 Stocks:Stockmodel[];
 PortfolioStocks : Stockmodel[];
 constructor(private stockService: StockService, private formBuilder: FormBuilder) {
 }
ngOnInit() {
 // this.GetActiveStocks();
 this.GetDashboardPortfolioData();
 }
 GetDashboardPortfolioData()
 {
 this.stockService.GetStocks("http://localhost:44311/api/GetDashboardPortfolioData")
 .toPromise().then(data => {
 return this.PortfolioStocks = data;
 });
 }
 public profitLossChart: any = {
    chart: {
    type: 'pie',
    },
    title: {
    text: 'Profit/Loss Chart'
    },
    credits: {
    enabled: false
    },
    series: [],
   }
 
    GetProfitLossChart(){
    let totalInvestment:number=0;
    let totalGain:number=0;
    this.PortfolioStocks.forEach(row => {
    totalInvestment+=row.TotalInvested;
    totalGain += row.CurrentValue;
    });
    this.GetTopGainerChart();
    this.GetTopLoserChart();
    this.profitLossChart.series =[{
    data: [{
    name: 'Total Investment#',
    y: totalInvestment,
    },
    {
    name: 'Current Value',
    y: totalGain,
    }]
    }]
    Highcharts.chart('containerProfitLoss', this.profitLossChart);
 }
 public topGainerChart: any = {
 chart: {
 type: 'line',
 },
 title: {
 text: 'Top Gainer'
 },
 credits: {
 enabled: false
 },
 xAxis: {
 categories: [],
 },
 yAxis: {
 title: {
 text: ''
 },
 },
 series: [],
}
 GetTopGainerChart() {
 let length = this.PortfolioStocks.length;
 if (length > 0) {
 this.stockService.GetGainerLoserStockData('http://localhost:44311/api/GetGainerLoserStockData', this.
PortfolioStocks[length - 1].StockId, "Monthly")
 .toPromise().then(data => {
    const stockData = [];
    const dates = [];
    data.forEach(row => {
    const temp_row = [
    row.High,
    ];
    dates.push(row.Date);
    stockData.push(row.High);
    });
    var dataSeries = [];
    for (var i = 0; i < stockData.length; i++) {
    dataSeries.push(
    stockData[i]
    );
    }
    this.topGainerChart.series = [{ data: dataSeries, name:
   this.PortfolioStocks[length - 1].StockId }]
    this.topGainerChart.xAxis.categories = dates
    Highcharts.chart('topGainerChart', this.
   topGainerChart);
    },
    error => {
    console.log('Something went wrong.');
    });
    }
    }
    public topLoserChart: any = {
    chart: {
    type: 'line',
    },
    title: {
        text: 'Top Loser'
        },
        credits: {
        enabled: false
        },
        xAxis: {
        categories: [],
        },
        yAxis: {
        title: {
        text: ''
        },
        },
        series: [],
        }
        GetTopLoserChart() {
        let length = this.PortfolioStocks.length;
        if (length > 0) {
        this.stockService.GetGainerLoserStockData('http://localhost:44311/api/GetGainerLoserStockData',
       this.PortfolioStocks[0].StockId, "Monthly")
        .toPromise().then(data => {
        const stockData = [];
        const dates = [];
        data.forEach(row => {
        const temp_row = [
        row.High,
        ];
        dates.push(row.Date);
 stockData.push(row.High);
 });
 var dataSeries = [];
 for (var i = 0; i < stockData.length; i++) {
 dataSeries.push(
 stockData[i]
 );
 }
 this.topLoserChart.series = [{ data: dataSeries,
name: this.PortfolioStocks[0].StockId }]
 this.topLoserChart.xAxis.categories = dates
 Highcharts.chart('topLoserChart', this.topLoserChart);
 },
 error => {
 console.log('Something went wrong.');
 });
 }
 }
}

3 个答案:

答案 0 :(得分:2)

我在这里不确定,但是您没有对诺言所返回的data的安全检查。那是发生错误的地方吗?如果data未定义,则data.forEach将引发错误。

答案 1 :(得分:1)

尝试调试

var AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-1'});
var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

var params = {
  ExpressionAttributeNames: {
   "#T": "topics", 
   "#S": "subscribers"
  }, 
  ExpressionAttributeValues: {
    ":vals": {
      L: [
        { N: "123" },
        { N: "456" }
      ]
    }
  }, 
  Key: {
   'server-id': { S: '123345678' }
  }, 
  ReturnValues: "ALL_NEW", 
  TableName: 'dummy-table',
  UpdateExpression: "SET #T[0].#S = list_append(#T[0].#S, :vals)"
 };

ddb.updateItem(params, function(err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});

也许是响应体内的东西

.toPromise().then(data => {
    //console.log(data)
)}

因此您需要通过以下方式访问数据:

{
  data: {},
  status: 200
}

答案 2 :(得分:0)

您正在以异步方法设置PortfolioStocks,这意味着您不确定在执行forEach时是否设置了该值。

我建议您使用BehaviorSubject方法和rxjs

...
PortfolioStocks = new BehaviorSubject<Arry<Stockmodel>([]);
...
 GetDashboardPortfolioData() {
     this.stockService.GetStocks("http://localhost:44311/api/GetDashboardPortfolioData")
         .toPromise().then(data => {
             this.PortfolioStocks.next(data);
          });
 }
...
    this.PortfolioStocks.pipe(filter(portfolioStocks => Array.isArray(portfolioStocks)))
        .subscribe(portfolioStocks => {
            portfolioStocks.forEach(row => {
                totalInvestment+=row.TotalInvested;
                totalGain += row.CurrentValue;
            });
        })