首页 文章

在生命周期钩子中订阅observable后,类变量是未定义的

提问于
浏览
0

我尝试在我的组件类中设置变量(json对象) . ngOnInit订阅可观察服务并设置组件变量 . 当我尝试在组件模板中使用点表示法访问此变量时,出现此错误:

无法读取未定义的属性'count_runs'

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是:

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

1 回答

  • 2

    您需要利用Elvis运算符:

    {{avgTime?.count_runs}}
    

    因为avgTime是异步设置的,并且最初是未定义的...

相关问题