[Fixed] cannot loop and assign api values in constructor


I have a export type as below:

export type Program{
key: string; value: string;

I have array values returning from api as below:

apival = ["abc", "xyz" ...etc]

In my component I am doing this in my constructor

program: Program[];

constructor(private service: Service){
getval = service.apival;
getval.forEach((a) => {
key: a, 
value: ""

Now I want to assign the returned array values as key to the program type. I am doing this with a forEach loop. But, I am getting the following error:

"Cannot read property 'push' of undefined" 

Note:I tried to do this in service itself, but I am getting this error : "Cannot Instantiate cyclic dependency"

Any idea, why this happens and what is the best way to assign the getval to the programs[]. Either in service or component.

I dont want to do it on OnInit()


Your program: Program[]; needs to be initialized like this program: Array<Program> = new Array<Program>(). Also you could use a map and get a new array.

this.program = getval.map(a=>{return {key:a, value:""}});

Leave a Reply

(*) Required, Your email will not be published