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



我试图用Angular和API制作一个highchart应用程序,我不知道为什么会出现这个错误:错误类型错误:无法读取DashboardComponent.GetProfitLossChart(47(中未定义的属性'forEach'。我的代码中没有任何错误,但我在谷歌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.');
});
}
}
}

这里我不确定,但您没有对promise返回的data进行安全检查。这就是错误发生的地方吗?如果data未定义,则data.forEach将抛出错误。

尝试调试

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

也许反应体内部有类似的东西

{
data: {},
status: 200
}

所以你需要通过获取数据

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

您在异步方法中设置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;
});
})

最新更新