Not able to copy the contents of one array to another in Angular 5

Issue

I have an empty array defined like this in my component:

private dtoList=[];

I call a service with HttpClient to fetch data from the backend that returns and object containing a list:

    this.appService.getData()
        .subscribe((response) => {
          let value = response;
            //1st way
          this.dtoList = response['dtoList'];
          //2nd way
          this.dtoList = cloneDeep(response['dtoList']);
   });

The response received in the value field is:

Object {success: false, description: null, dtoList: Array(2), status: null}

The list received in the response object is not getting copied in the target list.
The target list is always shown as undefined.

Any help would be appreciated.

Solution

The phenomenon that happens is not quite clear but if I copy the contents of the returned response in a separate method, it seems to work. So instead of copying the response contents in the anonymous subscribe function, I passed it to another method to copy. It worked this way.

this.myService.getData().subscribe((response) => {
        let values = response['dtoList'];
        this.copyValues(values);
});

// the copyvalues method

copyValues(list) {
    this.dtoList = list;
}

Answered By – Salman Kazmi

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.