简体   繁体   中英

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

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

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.

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.

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'?

refCompanies: ReferenceCompany[] = new ReferenceCompany();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM