1

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, 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

3
  • already answered here stackoverflow.com/a/58401023/7651583, use it like event?.total Commented Dec 7, 2022 at 6:33
  • in my case on the code above, I tried this.progress = Math.round(100 * event.loaded / event?.total); but the error is the same and it does not solve the error!!!! Commented Dec 7, 2022 at 7:18
  • and also use like this this.progress = Math.round(100 * event?.loaded / event?.total); but the error is still there Commented Dec 7, 2022 at 7:23

1 Answer 1

3

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.