I've tested this quite a bit and can't understand why below doesn't work. The problem is that after the @Input variable arrives and the user object is retrieved from the service, the ngIf in the template only outputs: "some random text" and none of the user object values. If I switch the ngIf line out with <div *ngIf="userList">{{userList.firstName}} {{userList.lastName}}
it works fine (the userList array has firstName and lastName elements too). For some reason it seems can't do it with the promise function getUser. I have tested the promise response with console.log and it is definitely retrieving the data object from the service. I know the tutorial does this type of thing this with routing, but I'm curious what I'm doing wrong here so I can understand what's happening.
import { Component, Input } from '@angular/core';
import { User } from './ViewModels/UserVM';
import { UserList } from './userList';
import { UserService } from './user.service';
@Component({
moduleId: module.id,
selector: 'user-form',
template: `
<div *ngIf="user">{{user.firstName}} {{user.lastName}} some random text</div>
`
})
export class UserFormComponent {
errorMessage: string;
user: User;
_selectedUser: UserList;
@Input()
set selectedUser(selectedUser: UserList) {
if (selectedUser) {
this._selectedUser = selectedUser;
this.getUser(selectedUser.id);
}
}
get selectedUser() { return this._selectedUser; }
constructor(private userService: UserService) { }
getUser(id: number) {
this.userService.getUser(id).toPromise()
.then(user => this.user = user)
.catch(err => this.errorMessage = err);
}
}
-----UPDATE-----
Turns out I forgot that the User object is not completely flat and firstname and lastname are actually in user.Person.firstName, etc.