无法从控制台获取事件值



我无法从控制台获取事件总值。

控制台:

Object { type: 1, loaded: 1048105, total: 1334347 }
​
loaded: 1048105
​
total: 1334347
​
type: 1
​
<prototype>: Object { … }
app.component.ts:84:20
Object { type: 1, loaded: 1128059, total: 1334347 }
app.component.ts:84:20
Object { type: 1, loaded: 1227405, total: 1334347 }
app.component.ts:84:20
Object { type: 1, loaded: 1334347, total: 1334347 }

打字脚本:

onuploadFile( files : File[]): void{
console.log(files)
const formData = new FormData()
for(const file of files){
formData.append('files', file, file.name)
}
this.user.uploadFiles(formData).subscribe({
next: (event) => {
switch(event.type){
case HttpEventType.UploadProgress || HttpEventType.DownloadProgress:
console.log(event)
this.filestatus.percentage = Math.round( 100 * event.loaded / event.total) <-- (event.total says object is possibly 'undefined')
this.filestatus.status = 'progress'
break;
case HttpEventType.Response:
console.log(event)
this.filestatus.percentage = 0
this.filestatus.status = 'done'
break;
}
},
error: (e) => console.log(e),
complete: () => console.log('done uploading')
})
}

错误:对象可能是"未定义">

那么我怎样才能把这个数字除以得到百分比值呢。

要完全理解发生了什么,您需要向我们展示this.user.uploadFiles函数的返回类型,但我100%相信total在该类型中被标记为可选,因此Typescript编译器会引发错误,因为total可以是null/undefined,在这种情况下,您会得到运行时错误。尽管您可以在控制台中看到total被填充,但并不能保证每个对象都会有它,至少您正在将它与从uploadFiles返回的对象类型的编译器进行通信。

如果total始终存在于对象中,则根据需要进行标记在从uploadFiles返回的类型/类/接口中,或使用非null断言运算符(!(将total标记为非null:

this.filestatus.percentage = Math.round( 100 * event.loaded / event.total!) // ! at the end 

最新更新