Reputation: 103
I know how to render a list of objects in a template using NgFor, but I can't find any info on displaying a single object that isn't in an array.
I have an API end point that returns the user profile, through my ProfileService:
find() {
return this.http.get('/api/user/22/profile.json');
}
My component is setup like this:
export class ProfileListComponent implements OnInit {
profile: any;
constructor(private profileService: ProfileService) { }
loadProfile() {
this.profileService.find()
.subscribe(response => this.profile = response.json());
}
ngOnInit() {
this.loadProfile();
}
}
In my template, I don't want to use NgFor, I just want to display the profile's attributes like:
{{ profile.name }}
How do I accomplish this? Right now, I get an undefined error, as if profile doesn't exist.
Upvotes: 0
Views: 727
Reputation: 691755
The profile
field stays undefined until the http response comes back and the callback initializing it is invoked. That's why you get that error. Use ngIf
to avoid diplaying the profile while it's not there yet, or use
{{ profile?.name }}
Upvotes: 1