[英]Why am I receiving “ERROR TypeError: Cannot read property 'length' of undefined” on a defined array?
I defined, initialized(TWICE) my array, yet i am getting "ERROR TypeError: Cannot read property 'length' of undefined" at runtime. 我定义了数组,并初始化了(TWICE),但是在运行时出现“ ERROR TypeError:无法读取未定义的属性'length'的信息”。
I already tried to check if the array was defined as you can see in my code, still angular is just trolling me. 我已经尝试检查数组是否已定义(如您在我的代码中看到的那样),但是angular仍在拖曳我。 I already tried all solutions like changing the sintax to "filesToUpload && filesToUpload?.length > 0" or any possible combination, however Angular is just not working properly imo. 我已经尝试了所有解决方案,例如将sintax更改为“ filesToUpload && filesToUpload?.length> 0”或任何可能的组合,但是Angular在imo上无法正常工作。
component.html file component.html文件
<ng-container *ngIf="undefined !== filesToUpload && filesToUpload.length > 0">
<button (click)='uploadImages()'
class="btn btn-success"
type="button">
<i class="fas fa-upload"></i>Upload
</button>
<button (click)='cancelUpdate()'
class="btn btn-danger"
type="button">Cancel</button>
</ng-container>
This is my component.ts file 这是我的component.ts文件
export class ImageGalleryUploadComponent implements OnInit
{
filesToUpload: File[] = [];
ngOnInit() {
this.filesToUpload = []
}
}
is this an angular bug? 这是有角度的错误吗? or has something to do with component lifecycle? 还是与组件生命周期有关?
Try this, somewhere you are assigning undefined
to your Array object. 尝试此操作,在将undefined
分配给Array对象的地方。
<ng-container *ngIf="filesToUpload && filesToUpload != 'undefined' && filesToUpload.length > 0">
Though it's not a good practice, just try it once and if confirmed then cross-check in your code. 尽管这不是一个好习惯,但是只需尝试一次,如果确认,则交叉检查代码。
使用安全的导航运算符尝试这种方式,它将一次性处理null和lentgh文件,
<ng-container *ngIf="filesToUpload && filesToUpload?.length > 0">
Just do it once like: 只需执行一次即可:
export class ImageGalleryUploadComponent implements OnInit
{
filesToUpload: File[] = [];
}
I have faced this issue as well. 我也面临这个问题。 Removing the re-initialisation from ngOnInit
should fix the issue. 从ngOnInit
删除重新初始化应该可以解决此问题。 And don't worry every time the component is initialised it will be set to []
. 并且不用担心每次组件初始化时都会将其设置为[]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.