angulartypescriptservicecomponentsresponse

Issue with reading response of type Object in Angular Component


I am having issue as described below:

I have user-details-with-addresses.ts file and this has two properties:

export class userDetailsWithAddresses{
    user: User;
    addresses: UserWithAddresses[];
}

I have user-component.ts where I call service and fetch a response which is of type userDetailsWithAddresses[].

export class userComponent implements OnInit {
  data: userDetailsWithAddresses[] = null;

 getArchiveUserDetails(id: string){
    this.userService.getUserListWithAddressById(id).subscribe(response => {
      console.log(response);
      this.data=response;
      console.log(this.data[0]);
      console.log(this.data.user);
    });

  }

}

I do see response in the chrome developer tools. I even see this.data.user value in the developer tools which is User object.

this.data.addresses has three addresses objects. I want to read both user and addresses list. However, when I check this.data[0] as shown above, it's undefined.

When I check this.data.user in the code above, it says Property 'user' does not exist on type 'userDetailsWithAddresses[]'.

Kindly, help me resolve this issue.


Solution

  • You should set data to just the interface userDetailsWithAddresses, the problem was caused because it was set to an array of userDetailsWithAddresses (userDetailsWithAddresses[]). When it looks like the response a single object.

    Because you are able to see this.data.user in the dev tools console, that means data property is an object, to access the inner addresses, we can access it like this.data.addresses[0].

    export class userComponent implements OnInit {   
      data: userDetailsWithAddresses = null; // <- changed here!
    
      getArchiveUserDetails(id: string){
        this.userService.getUserListWithAddressById(id).subscribe(response => {
          console.log(response);
          this.data=response;
          console.log(this.data.addresses[0]); // <- changed here!
          console.log(this.data.user);
        });
    
      }
    
    }