开发者

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

 this.progress = Math.round(100 * event.loaded / event.total);

the error is event.total section here is my complete code in typescript

import { HttpClient, HttpEventType, HttpErrorResponse } from '@angular/common/http';
import { Component, EventEmitter, OnIni开发者_开发技巧t, 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. 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))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜