class 在生命周期钩子中订阅 observable 后变量未定义

class variable is undefined after subscribing observable in lifecycle hook

我尝试在我的组件 class 中设置一个变量(json 对象)。 ngOnInit 订阅一个可观察的服务并设置组件变量。 当我尝试在组件模板中使用点符号访问此变量时,出现此错误:

Cannot read property 'count_runs' of undefined

observable 有一个类型注释(avgTime 接口)。

平均-time.ts

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

stats.service.ts

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

@Injectable()
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());
  }
}

平均-time.component.ts

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

@Component({
  selector: 'avg-time',
  template: `
    <h1>AvgTimeComponent</h1>
    {{avgTime.count_runs}}
  `,
  providers: [StatsService]
})
export class AvgTimeComponent implements OnInit {
  avgTime: AvgTime;

  constructor(private _statsService: StatsService) { }

  ngOnInit() {
    this._statsService.getAvgTime()
        .subscribe(avgTime => this.avgTime = avgTime);
  }
}

当我在 ngOnInit 中伪造服务响应时它也不起作用:

平均-time.component.ts

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

我的 stats.service.ts 来自后端的 return 是:

[{"AVG_RUNTIME_MILLIS":55,"COUNT_RUNS":5400}]

您需要利用 Elvis 运算符:

{{avgTime?.count_runs}}

因为 avgTime 是异步设置的并且一开始是未定义的...