Why is Angular component property undefined after http.get

Răzvan Source

Why is "this.Trails" undefined in the constructor after http.get?

The http.get is succesfull, but "this.Trails" is undefined all the way. Still, in my page I am able to output the items. I don't understant this.

import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';

    selector: 'salvamont',
    templateUrl: './salvamont.component.html'
export class SalvamontComponent {
    public Trails: HikingTrail[];
    constructor(http: Http, @Inject('BASE_URL') baseUrl: string) {
        http.get(baseUrl + 'api/SampleData/HikingTrails')
          .subscribe(result => { 
            this.Trails = result.json();
          error => console.error(error));

        if (this.Trails != undefined) {
            console.log("has items");

class HikingTrail {
   //some members


answered 6 months ago elvis_ferns #1

Http.get() is an async call which will get processed on next tick (after it is resolved or rejected)

if (this.Trails != undefined) {
   console.log("has items");

The above code is executed before the subscription

this.Trails = result.json();

Thus undefiend

comments powered by Disqus