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.

Seyon Seyon
  • 527
  • 4
  • 14
  • 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 – Madhawa Priyashantha Sep 07 '21 at 01:59
  • https://stackoverflow.com/questions/41139763/how-to-declare-a-fixed-length-array-in-typescript – sinanspd Sep 07 '21 at 02:00
  • This is not java, you don't create array like that in javascript or typescript. Just `this.mygroupB = [];` is enough. – Ricky Mo Sep 07 '21 at 02:05

1 Answers1

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);
    }
}
dom.macs
  • 776
  • 7
  • 15