0

trying to access the child member(is an array) of parent interface. But getting undefined.

export class Address {
    id: number;
    city: string;
    state: string;
}

import { Address } from './address';
export class User {
    id: number;
    name: string;
    alladdresses: Address[];
}

in my component - the declaration are

  users: User[] = [];
  address: Address[] = [];

and my http.get is

    selectUser(user: User) {
    let url = "http://localhost:8080/users/" + user.id
    this.http.get<User>(url).subscribe(

      res => {
        //console.log(res);
        this.selectedUser = res;
        console.log('selected user is:', this.selectedUser);

      },
      error => {
        console.log('error while getting user for ', user.id);
      },
      () => {
        console.log('complete');
      }
    );
  }

and the json response of user is enter image description here

here the selected user I am displaying on the page, and some action on page calling another function to access the addresses - the array

createAddress() {
    let newAddress: Address = {
      id: null,
      city: "new city",
      state: "new state"
    }
    console.log(this.selectedUser)
    let address: Address[] = this.selectedUser.alladdresses
    //address.push(newAddress);
    console.log(address);
  }

But the array is undefined, not where waht going wrong. enter image description here

3
  • Shouldn't you have this.selectedUser.addresses instead of this.selectedUser.alladdresses in your console.log? Commented Jun 12, 2019 at 16:21
  • Unless you want to manually instantiate the class instances, you should define server response types as interfaces. Commented Jun 12, 2019 at 16:44
  • all confusion with alladdresses: Address[]; now I have changed to addresses Commented Jun 12, 2019 at 17:18

1 Answer 1

1

Looks like there's a mismatch between the data your http.get method is returning and what you are expecting. Your api is returning the addresses named as addresses whereas you are expected alladdresses.

Sign up to request clarification or add additional context in comments.

2 Comments

all confusion with alladdresses: Address[]; now I have changed to addresses
this helped me out. great stuff

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.