1

I am having troubles with displaying a property of an object, received through Http get request in Angular. I am trying to call HTTP request in ngOnInit() method and that seems to work fine: I receive back the object I need. But then I am having troubles to display it in the http file (the property is undifined). It seems that I can't connect the observable to the object property. What am I doing wrong?

The Component:

import { Component, OnInit } from '@angular/core';
import {Package} from "../shared/package";
import { Http} from "@angular/http";
import 'rxjs/Rx';

@Component({
  selector: 'app-basket',
  templateUrl: './basket.component.html',
  styleUrls: ['./basket.component.css']
})
export class BasketComponent implements OnInit {

package: Package;
  private baseUrl: string = 'https://basket-211b4.firebaseio.com/.json';

  constructor(private http: Http) { }

  ngOnInit() {
    this.http.get(`${this.baseUrl}`).subscribe(
      (result) =>{
      this.package = result.json();
        console.log(this.package);
      }
    )
  }

The Http file:

 <li class="row totals">
        <span class="price" >{{ package.id }}</span>
      </li>

The Package class:

import {User} from "./user";
import {Service} from "./service";
export class Package {
  constructor(public id: number, public totalCost: number, public dateCreated: string, public user: User,
              public services: Service[]){}
}

The console error: Error in ./BasketComponent class BasketComponent - inline template:31:29 caused by: Cannot read property 'id' of undefined

The object displayed in the console: Object {dateCreated: "2017-05-14T18:47:56.000+0000", id: 1, services: Array(3), totalCost: 3600, user: Object}

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
angie
  • 13
  • 1
  • 3
  • Http sends AJAX requests. The first A in AJAX means *asynchronous*. So the package field is not populated yet when the component is first displayed. It's only populated later, when the HTTP response comes back and the callback function passed to subscribe is being executed. Use `package?.id`. Or use *ngIf to only display the package nce it's available. – JB Nizet May 21 '17 at 12:23

1 Answers1

1

You can use Safe navigation (?) operator to display the properties,

<li class="row totals">
    <span class="price" >{{ package?.id }}</span>
</li>
Jayakrishnan
  • 4,232
  • 2
  • 23
  • 35