Volkan BİÇER
Volkan BİÇER

Reputation: 71

Data not updated on http response

After http response comes I updated "user" field but it causes an error.

Error:Cannot read property 'firstName' of undefined in [ name filed {{user.firstName}} in ProfileComponent@5:3]

If I write<p> {{user | json}} </p> I see the value of "user" field.

Component

export class ProfileComponent implements OnInit {

    title:string = "Profile";
    public user:User;

    constructor(private _stateService:StateService,
                private _profileService:ProfileService) {
    }

    ngOnInit():any {
        this._profileService
            .getMe()
            .subscribe(
                user=> this.user = user
            )
    }
}

Html

<p>{{ user.firstName }}</p>

Upvotes: 0

Views: 52

Answers (2)

micronyks
micronyks

Reputation: 55443

<p> {{user?.firstName}} </p>

Look at here. This is my implementation (yours could be different).

http://plnkr.co/edit/NmxaIzOUmmnMriJeSnrA?p=preview - (Click on friends Tab)

try to remove Elvis operator (?) and see you'll get error. With (?) operator it is working fine.

Upvotes: 1

Shailesh
Shailesh

Reputation: 490

   Try <p [innerHtml]="user.firstname"></p>.

Also initialise the user in the constructor to a default value.

    constructor(private _stateService:StateService,
                private _profileService:ProfileService) {
        this.user = new User();// assuming user class has default constructor
    }

Upvotes: 0

Related Questions