[英]Angular 4 - ERROR in Cannot read property 'length' of undefined
I'm getting this error as I'm trying to get a median of an array. 我在尝试获取数组的中位数时遇到此错误。
moniesService.ts moniesService.ts
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ReferenceCompany } from '../../shared';
@Injectable()
export class ReferenceCompanyService {
basisPoint: number;
medianRate: number;
highMiddle: number;
lowMiddle: number;
rateList: Array<number> = [];
refCompanies: ReferenceCompany[];
index: number;
constructor(private http: HttpClient) { }
// my HTTP calls which I erased them.
// Median Rate
addRateToArray() {
this.index = 0;
for (const i of this.refCompanies) {
this.rateList.push(this.refCompanies[this.index].fx_rate);
this.index++;
}
for (let j = 0; j <= this.rateList.length; j++) {
console.log(this.rateList[j]);
}
}
// Calculate the Median and Basis point
median() {
this.addRateToArray();
this.rateList.sort((a, b) => a - b);
this.lowMiddle = Math.floor((this.rateList.length - 1) / 2);
this.highMiddle = Math.ceil((this.rateList.length - 1) / 2);
this.medianRate = (this.rateList[this.lowMiddle] + this.rateList[this.highMiddle]) / 2;
this.basisPoint = this.medianRate / 10000;
}
}
referenceCompany.ts interface referenceCompany.ts接口
export class ReferenceCompany {
_id: string;
name: string;
fx_rate: number;
}
So the logic is, I have reference companies in my database which each company has an id, name and fx_rate. 因此,逻辑是,我的数据库中有参考公司,每个公司都有一个id,名称和fx_rate。
So what I'm doing is i'm pushing each fx_rate from each company to temp array and from there I'm calculating the median. 因此,我正在做的是将每个公司的每个fx_rate推送到临时数组,然后从中计算中位数。
I am able to get the median rate, but the thing is when I click first on the button to get the median rate it gives me this error. 我可以得到中位数,但是问题是,当我首先单击按钮以获得中位数时,它给了我这个错误。
`ERROR in Cannot read property 'length' of undefined`
for 对于
`addRateToArray()`
and on the second click, I'm able to get the median rate with no error. 在第二次单击时,我可以毫无错误地获得中位数。
what I'm doing wrong? 我做错了什么?
Since you're working with asynchronous data, you probably need to instantiate a new instance. 由于您正在使用异步数据,因此可能需要实例化一个新实例。 Have you tried instantiating a new reference of 'ReferenceCompany'? 您是否尝试实例化“ ReferenceCompany”的新引用?
refCompanies: ReferenceCompany[] = new ReferenceCompany();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.