Seyon Seyon
Seyon Seyon

Reputation: 567

How to create array of objects from another class in angular?

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.

Upvotes: 0

Views: 1768

Answers (1)

dom.macs
dom.macs

Reputation: 796

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);
    }
}

Upvotes: 1

Related Questions