显式设置组件变量类型时,Angular2服务不起作用

时间:2016-11-02 03:23:46

标签: angular service

出于某种原因,我收到了错误

Uncaught (in promise): Error: Error in http://localhost:3000/app/calendars/cal-nav.component.html:5:7 caused by: Cannot read property 'selectedDate' of undefined TypeError: Cannot read property 'selectedDate' of undefined

但是,当我没有定义类型而是实例化像workingData = {selectedDate : "nonsense"};这样的变量时,服务工作属性并显示日期。 为什么这样,以及最好的管理方式是什么?

CAL-nav.component.ts

import { Component, OnInit } from '@angular/core';
import { WorkingData } from '../working-data';
import { WorkingDataService } from '../working-data.service';

@Component({
  moduleId: module.id,
  selector: 'cal-nav',
  templateUrl: 'cal-nav.component.html',
  providers: [WorkingDataService]
})
export class CalNavComponent implements OnInit{

  // this is where the issue is apparently
  workingData : WorkingData;

  constructor(private _workingDataService: WorkingDataService) { }

  getWorkingData(): void {
    this._workingDataService.getWorkingData().then(workingData => this.workingData = workingData);
  }

  ngOnInit(): void {
    this.getWorkingData();
    console.log(this.workingData);
  }
}

工薪data.ts

export interface WorkingData{
  selectedDate: string,
  targetDate: string,
  selectedExercise: string
}

模拟工作-data.ts

import {WorkingData} from './working-data';

export const WORKINGDATA: WorkingData = {
  selectedDate: "Nov 1",
  targetDate: "Nov 11",
  selectedExercise: "Squat"
};

1 个答案:

答案 0 :(得分:2)

呈现视图时,workingData尚未解析,因为它以异步方式解析。使用*ngIf首先检查workingData是否未定义:

<div *ngIf="workingData">
  <!-- other stuff using workingData -->
</div>

或者使用Angular安全导航操作符?.,这是一种流畅且方便的方法来防止属性路径中的空值和未定义值。在这里,如果workingData对象为null,则保护视图呈现失败:

<stuff>{{ workingData?.selectedData }}</stuff>