Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.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
意外执行Ngonit Angular 4?_Angular_Angular5 - Fatal编程技术网

意外执行Ngonit Angular 4?

意外执行Ngonit Angular 4?,angular,angular5,Angular,Angular5,我向服务器发出了请求 ngOnInit() { this.service.get(1).subscribe((response) => { this.whenDateCurrent = new DateCustomDate(); }); } 在这个组件中,我还有一个返回this的方法 public getCurrentDate(): string { return this.whenDateCurrent.prev.day; } 我从模板调用此函数: <input

我向服务器发出了请求

ngOnInit() {

this.service.get(1).subscribe((response) => {
   this.whenDateCurrent = new DateCustomDate();
});
}
在这个组件中,我还有一个返回this的方法

public getCurrentDate(): string {
    return this.whenDateCurrent.prev.day;
}
我从模板调用此函数:

<input mdInput readonly class="dateRange" name="dateRange" [value]="getCurrentDate()">

问题是在加载之前调用了函数
getCurrentDate()
this.service.get(1).subscribe((响应)=>{}

因此,它调用了一个错误:

无法读取未定义的属性“prev”


如果使用*ngIf仅在数据存在时加载元素会怎么样?这样,getCurrentDate()方法将仅在数据存在时调用

确保将WhenDacCurrent初始化为null,例如:

whenDateCurrent?: Date = null;

constructor() {

}

ngOnInit() {
  this.service.get(1).subscribe((response) => {
    this.whenDateCurrent = new DateCustomDate();
  });
}

public getCurrentDate(): string {
    return this.whenDateCurrent.prev.day;
}
模板:

<input *ngIf="whenDateCurrent" mdInput readonly class="dateRange" name="dateRange" [value]="getCurrentDate()">


您是否尝试将其移动。WhenDataCurrent在服务调用之外?您还尝试了什么?您是否有理由将输入的值设置为函数的返回值,而不是可以在其他位置设置的变量?我尝试过,正如我所知,同样的结果首先应该被称为ngOnInit,但称为
getCurrentDate()
为什么您必须使用函数作为输入框值?可能需要将所有代码放入构造函数中?我使用函数返回输入框中的当前日期,确保whenDateCurrent开始时为空。我已编辑了我的答案。请让我知道这是否有帮助。您知道它在Facebook中是如何工作的,当页面加载时,它会显示空的灰色块代替内容您可以通过执行相反的逻辑*ngIf=“!WhenDatacurrent”来显示任何类型的元素。当数据从服务返回时,此元素将被删除,并且*ngIf=“WhenDatacurrent”元素将被添加。但它仍然是隐藏元素,它仍然是空的,我需要显示它,就像这里的灰色块一样,这是一个非常小的示例,5秒后,值将被更改,您将看到第二个div。