Passing object as parameter to a second page


#1

I have problems trying to pass an object and show its properties on a second page. Something like this:

Home.html
------------------
<ion-list>
  <button ion-item *ngFor='let u of users;' (click)='onUser(u)'>
    <ion-avatar item-left>
      <img [src]='u.photo'>
    </ion-avatar>
    <h2>{{u.name}} {{u.lastName}}</h2>
    <p>{{u.phone}}</p>
  </button>
</ion-list>
Home.ts
------------------
public users: Array<any> = [];

constructor(userService: UserService) {
    userService.getUsers().subscribe(res => { 
        this.users = res.users;
    });
}
onUser(user: any) {
    this.nav.push('User', {
        user: user
    });
}
User.ts
------------------
public user: any = {};
constructor(params: NavParams) {
    this.user = params.get('user');
}
User.html
------------------
<ion-list>
    <ion-avatar item-left>
        <img [src]='user.photo' />
    </ion-avatar>
    <h2>{{user.name}} {{user.lastName}}</h2>
</ion-list>

It is too simple, just get data from a service, when click a button it push other page and pass the currently user with its properties. This user might be shown on User page. But I got this error:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'photo' of undefined
TypeError: Cannot read property 'photo' of undefined
    at Object.eval [as updateRenderer] (User.html:12)

What I have to do is on User.ts instead of declare my variable like this:

public user: any = {}

do:

public user: any = {
    name: '',
    lastName: '';
    photo: ''

But for this particular case. My API has a lot of properties and I need declare user variable with empty properties to do it works.
I do this:

public user: any = dummyUser();
...
function dummyUser() {
    return {
        name: '',
        lastName: ''
        photo: ''
    }
}

The same but inside a function.
It is really necessary do this? Am I doing something wrong?


#2

In User.ts you are initializing user with a legitimate value in the constructor, so no, it should not be needed to initialize a dummy separately. Make sure that user really is coming in through the NavParams.


#3

Well in the example of the post I use user but actually my application use contacts and this is:

line 10 declaring an empty object.
line 16 print contact param from navParams. It is shown on console like contact.ts:16.
line 17 assign contact param to member variable contact.

If I assign empty properties to contact of Contact class it works.


#4

Well, it was too embarrassing , just was a typo on contact template. I had cotact.name and it was true: cannot read property name of undefined. cotact doesn’t exists.