[英]how to solve error Object is possibly 'undefined' angular 14 typescript?
in the previous version of angular the bellow code normally working for me, but now in angular 14 it gives me the error Object is possibly undefined
在以前版本的 angular 中,下面的代码通常对我有用,但现在在 angular 14 中它给了我错误
Object is possibly undefined
this.progress = Math.round(100 * event.loaded / event.total);
the error is event.total
section here is my complete code in typescript错误是
event.total
部分是我在 typescript 中的完整代码
import { HttpClient, HttpEventType, HttpErrorResponse } from '@angular/common/http';
import { Component, EventEmitter, OnInit, Output } from '@angular/core';
@Component({
selector: 'app-upload',
templateUrl: './upload.component.html',
styleUrls: ['./upload.component.css']
})
export class UploadComponent implements OnInit {
progress: number;
message: string;
@Output() public onUploadFinished = new EventEmitter();
constructor(private http: HttpClient) { }
ngOnInit() {
}
uploadFile = (files) => {
if (files.length === 0) {
return;
}
let fileToUpload = <File>files[0];
const formData = new FormData();
formData.append('file', fileToUpload, fileToUpload.name);
this.http.post('https://localhost:5001/api/upload', formData, {reportProgress: true, observe: 'events'})
.subscribe({
next: (event) => {
if (event.type === HttpEventType.UploadProgress)
this.progress = Math.round(100 * event.loaded / event.total);
else if (event.type === HttpEventType.Response) {
this.message = 'Upload success.';
this.onUploadFinished.emit(event.body);
}
},
error: (err: HttpErrorResponse) => console.log(err)
});
}
}
can anyone help me with how to solve this error????谁能帮我解决这个错误???? thanks
谢谢
The value is returning from Http
request, so it really can be undefined
, and in case it will return undefined
the value that will return to the progress
variable will NaN
.该值是从
Http
请求返回的,所以它确实可以是undefined
,如果它将返回undefined
,则返回到progress
变量的值将是NaN
。 so, you can simply wrap it with condition:所以,你可以简单地用条件包装它:
if(event?.loaded && event?.total ) {
this.progress = Math.round(100 * event.loaded / event.total)
}
or, give it a default value:或者,给它一个默认值:
this.progress = Math.round(100 * (event.loaded || 1) / (event.total || 1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.