【问题标题】:I have a problem about length. ERROR TypeError: Cannot read property 'length' of undefined我对长度有疑问。错误类型错误:无法读取未定义的属性“长度”
【发布时间】:2019-05-13 02:09:47
【问题描述】:

是否应该从角度权继承长度?以及为什么 if (fileList.length> 0) MyPostsComponent.html: 7 ERROR TypeError: Cannot read the 'length' of undefined property.

onFileSelection(event){
  const fileList: FileList = event.target.filse;

  if (fileList.length > 0){
    const file: File = fileList[0];
    this.myFire.uploadFile(file).then(data => {
      //TO DO
      this.notifier.display('success','Picture Uploaded!');
      console.log(data['fileUrl']);
    })
    .catch(err => {
      this.notifier.display('error', err.message);
    });
  }
}

在我的 html 代码上

<input type="file" (change)="onFileSelection($event)" placeholder="Upload a file" accept=".png, .jpeg, .jpg">

【问题讨论】:

  • 如果以下答案不起作用,请检查 fileList 包含的内容。
  • 我刚刚检查过了。 @rorschach 的答案是正确的。它应该是 const fileList: FileList = event.target.files; 但在检查任何对象的长度之前,您仍然需要检查 null | undefined

标签: angular typescript firebase firebase-storage


【解决方案1】:

你可以在你的代码中改变......

const fileList: FileList = event.target.files || [];

我希望这会奏效。

【讨论】:

    【解决方案2】:

    这是因为你的文件列表未定义,首先你应该检查文件列表是否未定义

    onFileSelection(event){
          const fileList: FileList = event.target.filse;
    
          if (fileList && `enter code here`fileList.length > 0){
            const file: File = fileList[0];
            this.myFire.uploadFile(file).then(data => {
              //TO DO
              this.notifier.display('success','Picture Uploaded!');
              console.log(data['fileUrl']);
            })
            .catch(err => {
              this.notifier.display('error', err.message);
            });
          }
        }
    

    【讨论】:

      【解决方案3】:

      const fileList: FileList = event.target.filse;

      您似乎有一个错字,这将导致 fileList 成为 undefined 作为事件的目标肯定不包含名为 filse 的属性。

      【讨论】:

        【解决方案4】:

        表示 fileList 为 null ,添加 null 检查如下,

        if (fileList && fileList.length > 0){
        

        【讨论】:

          猜你喜欢
          • 2018-04-25
          • 2017-11-25
          • 1970-01-01
          • 2022-11-12
          • 2015-05-08
          • 2020-06-02
          • 2013-11-24
          相关资源
          最近更新 更多