0

I have two angular classes called class A , B and I have an angular component

export class B {
    id:String;
    Name:String;
}

My class A , Where I am passing data from a component. Where Component retrieves the data from httpclient request. Additionally I am trying to create an array of objects of class B . Which will have the size of data

export class A {

  mygroupB : B[];

  setData(data:any){
      if((data.length) >0){
        this.mygroupB = new B[data.length];
      }else return;

  }
}

But When I am running the code I am getting an error "B[data.length] is not a constructor" . I can't figure out, what is the mistake here. Thanks in advance.

3
  • you should create object as new B(); don't pass any arguments as your class B has no constructer to accept it.You can use map or loops to create a array Commented Sep 7, 2021 at 1:59
  • stackoverflow.com/questions/41139763/… Commented Sep 7, 2021 at 2:00
  • This is not java, you don't create array like that in javascript or typescript. Just this.mygroupB = []; is enough. Commented Sep 7, 2021 at 2:05

1 Answer 1

1

The first issue is you didn't instantiate your mygroupB before assigning the value. The next issue is you are trying to assign the value of data which is type any directly to mygroupB which has a type of B.

In the solution below, I instantiated mygroupB before iterating the values of data and then pushing it to the mygroupB array.

setData(data: any) {
    if (data.length > 0) {
      this.mygroupB = new Array<B>();
      data.forEach(e => {
        this.mygroupB.push({
          Name: e.Name,
          id: e.id
        });
      });
      console.log(this.mygroupB);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I'm glad I could help!

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.