Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
显式设置组件变量类型时Angular2服务不工作_Angular_Service - Fatal编程技术网

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

显式设置组件变量类型时Angular2服务不工作,angular,service,Angular,Service,由于某种原因,我得到了一个错误 Uncaught(承诺中):错误:错误http://localhost:3000/app/calendars/cal-html:5:7原因:无法读取未定义的属性“selectedDate” TypeError:无法读取未定义的属性“selectedDate” 然而,当我不定义类型,而是像这样实例化变量时,workingData={selectedDate:“胡说”}然后service works属性并显示日期为什么会这样?最好的管理方法是什么? cal-nav.c

由于某种原因,我得到了一个错误

Uncaught(承诺中):错误:错误http://localhost:3000/app/calendars/cal-html:5:7原因:无法读取未定义的属性“selectedDate”
TypeError:无法读取未定义的属性“selectedDate”

然而,当我不定义类型,而是像这样实例化变量时,
workingData={selectedDate:“胡说”}然后service works属性并显示日期为什么会这样?最好的管理方法是什么?

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);
  }
}
working-data.ts

export interface WorkingData{
  selectedDate: string,
  targetDate: string,
  selectedExercise: string
}
import {WorkingData} from './working-data';

export const WORKINGDATA: WorkingData = {
  selectedDate: "Nov 1",
  targetDate: "Nov 11",
  selectedExercise: "Squat"
};
mock-working-data.ts

export interface WorkingData{
  selectedDate: string,
  targetDate: string,
  selectedExercise: string
}
import {WorkingData} from './working-data';

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

渲染视图时,
工作数据
尚未解析,因为它是异步解析的。使用
*ngIf
首先检查
工作数据是否未定义:

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

要么1)这是一个异步问题,要么2)您的服务没有返回任何数据<代码>无法读取未定义的属性“selectedDate”
表示尚未设置变量workingData。当您使用selectedDate值启动它时,使用workingData.selectedDate显然会返回您设置的值。@VtoCorleone它必须是前者。I
console.log()
从服务中分配值后的数据,它显示
undefined
一次,然后显示服务中的正确对象。如果这是一个异步问题,我该如何着手解决它?