Eric Eric - 4 months ago 33
HTTP Question

Angular 2 (TypeScript): Unable to bind to object from http.get in HTML Template

Having a devil of a time figuring out why this is happening. I've got an A2 project set up using the CLI and I have the following component:

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

selector: 'app-user-profile-card',
templateUrl: 'user-profile-card.component.html',
styleUrls: ['user-profile-card.component.scss']
export class UserProfileCardComponent implements OnInit {

public person;

constructor(private http: Http) {

.map(res => res.json())
person => { this.person = person.person },
err => console.error(err),
() => console.log(

ngOnInit() {

The console log for shows the correct value, but when I try to bind to it from the template:

<div>{{ }}</div>

I get the following error:

undefined is not an object (evaluating '')

Any ideas on this?


That's because all http calls are asynchronous operations and you are trying to display in your template before data arrive. You can use safe navigation operator (?) to "protect" your template until data arrive:

    {{ person?.sex }}

You can also use ngIf directive:

<div *ngIf="person">
    {{ }}

This way, your div won't appear in DOM until variable person is populated. You can read more about safe navigation operator here and more about ngIf directive here.