1

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) => {
program.push({
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()

1

2 Answers 2

2

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:""}});
Sign up to request clarification or add additional context in comments.

Comments

0
program: Program[] = [];

Since program is a class variable, you need to use it with this keyword (this.program).

One line solution with ES6 would be:

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

map will iterate through your given array and returns a new array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.