mnlfischer mnlfischer - 1 year ago 95
TypeScript Question

class variable is undefined after subscribing observable in lifecycle hook

I try to set a variable (json object) in my component class. ngOnInit subscribing an observable service and set the component variable.
When I try to access this variable with dot notation in components template, I get this error:

Cannot read property 'count_runs' of undefined

The observable has a type annotation (avgTime Interface).


export interface AvgTime {
avg_runtime_millis: number;
count_runs: number;


import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { AvgTime } from './avg-time';
import { Observable } from 'rxjs/Observable';

export class StatsService {
constructor(private _http: Http) { }

private _avgTimeUrl = 'http://localhost:3002/api/reservation/avgTime';

getAvgTime() : Observable<AvgTime> {
return this._http.get(this._avgTimeUrl)
.map(res => res.json());


import {Component, OnInit} from '@angular/core';
import { AvgTime } from './avg-time';
import { StatsService } from './stats.service';

selector: 'avg-time',
template: `
providers: [StatsService]
export class AvgTimeComponent implements OnInit {
avgTime: AvgTime;

constructor(private _statsService: StatsService) { }

ngOnInit() {
.subscribe(avgTime => this.avgTime = avgTime);

It is also not working when I fake the service response in ngOnInit like:


ngOnInit() {
.subscribe(avgTime => {
this.avgTime = {
avg_runtime_millis: 150,
count_runs: 20

The return of my stats.service.ts from backend is:


Answer Source

You need to leverage the Elvis operator:


since avgTime is set asynchronously and is undefined at first...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download