Tips for resolving the issue of 'undefined' object in TypeScript with Angular 14

Previously, the below code worked fine in Angular for me. However, I am now encountering an error in Angular 14 stating Object is possibly undefined:

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

The issue seems to be with the event.total section. Here is my complete TypeScript code:

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)
    });
  }
}

Any help on how to resolve this error would be greatly appreciated. Thank you.

Answer №1

When the value is returned from an Http request, there is a possibility that it could be undefined. If it does return as undefined, the value assigned to the progress variable will be NaN. In order to address this issue, you can simply set up a conditional statement:

if(event?.loaded && event?.total ) {
   this.progress = Math.round(100 * event.loaded / event.total)
 }

Alternatively, you can assign a default value like so:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide to implementing Typescript Generics in modifier functions

I am searching for a solution to properly enforce strong typing in the following scenario. I believe Typescript Generics might be the way to go here. interface Person { name: string; age: number; } const person: Person = { name: "John", ...

Incorporating real-time checked checkbox values into a running list

When displaying a list of preferences as checkboxes, I encountered an issue with the binding part. I am trying to capture the IDs of the checkboxes that are checked. Here is my attempt, which unfortunately does not work: <div class="checkbox" *ngFor="l ...

When a form contains a ViewChild element, changes to the ViewChild element do not automatically mark the

Let's set the stage: MainComponent.html <form #someForm > <input type="text" name="title" [(ngModel)]="mainVar" /> <child-component /> <input type="submit" [disabled]="someForm.form.pristine" /> </form> ChildComp ...

How to handle type errors when using properties in Vue3 Single File Components with TypeScript

I've hit a roadblock while attempting to utilize properties in Vue3. Despite trying various methods, I keep facing issues during the type-check phase (e.g.: yarn build). The project I'm working on is a fresh Vue3-ts project created using Vite. B ...

What could be causing the Intellisense errors in Visual Studio 2015 that say "Cannot find module 'angular2/core'"?

Currently, I am utilizing Visual Studio 2015 Update 1 in conjunction with TypeScript 1.8.5. Within my ASP.NET MVC 4.6 Web Application, Angular2 is being used. The TypeScript compile options have been configured with the following settings: <PropertyG ...

Angular | Dynamic | Flexible | ResetConfiguration

Seeking Input What method is preferable for adjusting routes in Angular applications: utilizing routes.resetConfig(newRouteArray) or reloading the application on resize and dynamically creating routeArrays based on screen width? I welcome alternative sol ...

Upon setting up 'next-auth@beta' on the server, I encountered the [ERR_REQUIRE_ESM] Error

I have successfully integrated Next Auth into a Next Js application, which utilizes apollo client and apollo server with graphql. I have set up OAuth with Google using Next Auth v5 that supports App Router. On the frontend, I am able to handle sign-in, sig ...

`The term 'promise' is typically used to describe a type, yet in this context, it is being utilized as a value.`

I attempted to employ a promise for an Async call in my custom form validator, so I created a separate TypeScript file called usernameValidators.ts. import { Control } from 'angular2/common'; export class UsernameValidators { static should ...

What could be the reason for the 'tsc' command not functioning in the Git Bash terminal but working perfectly in the command prompt?

I recently installed TypeScript globally on my machine, but I am facing an issue while trying to use it in the git bash terminal. Whenever I run tsc -v, I encounter the following error: C:\Users\itupe\AppData\Roaming\npm/node: l ...

Use Angular or Laravel to translate API response data before it is sent to the frontend

I am currently working with an Angular frontend and a Laravel backend. I have an API that returns color names in an array, which I need to translate based on the default language setting. In both my frontend and backend, I have two JSON files named en.json ...

Picking up Angular component property values within a callback function from Google Charts

Trying to utilize the angular-google-charts library in Angular 13.2, I am working on creating a TreeMap with a customized tooltip feature. The GoogleChartComponent offers an options property called generateTooltip which requires a callback function. My goa ...

Explore all user-defined properties of a specified type using the TypeScript Compiler API

Consider the following model structure: interface Address{ country: string; } interface Author{ authorId: number; authorName:string; address: Address; } interface Book{ bookId:string; title: string; author : Author; } I want to iterate th ...

Encountering issues when integrating an Angular library project into the main project

Currently, I am facing an issue with a library project (let's call it X) that contains 2 projects within it (X-core, X-core-members). My goal is to utilize this library in another angular project called ABC. I have made the necessary links in the tsco ...

Is it possible to retrieve props in Vue without using methods?

<script lang='ts'> import GraphWorld from '@/components/GraphWorld.vue' // import { defineComponent } from "vue" export default { name: 'GraphView', props: ['people', 'prac'], compone ...

Increase the ngClass attribute's value

Is there a way to automatically increment a numeric value in a class using the ngClass directive? For example, can we achieve something like this: <some-element [ngClass]="'class-*'">...</some-element>, where the asterisk (*) will in ...

Tips for concealing a Div in an HTML document with the help of Angular

I need a solution to hide a div that contains only titles, while the div with the actual content is located in a different section <div> <b>Delivery Info\</b> <div class="custom-control">Delivery ID: </div ...

Mastering the nesting of keys in Typescript.Unlock the secrets of

I encountered a situation where the following code snippet was causing an issue: class Transform<T> { constructor(private value: T) {} } class Test<T extends object> { constructor(private a: T) {} transform(): { [K in keyof T]: Transfo ...

Storing geolocation information in local variables for future use

I am completely new to Nativescript (with Angular 2/TypeScript). My goal is to utilize the Nativescript geolocation plugin to track a user's location and store the data (latitude and longitude) for future use. Here is a snippet of my code: export cla ...

What is a more efficient way to differentiate a group of interfaces using an object map instead of using a switch statement?

As someone still getting the hang of advanced typescript concepts, I appreciate your patience. In my various projects, I utilize objects to organize react components based on a shared prop (e.g _type). My goal is to automatically determine the correct com ...

Sorting data in mongodb by multiple fields of a table

What is the best way to sort a response from one table based on a key from another table? Consider this scenario: We have a table called "user data" with fields such as { _id:objectId, name:string, age:number} Additionally, we have a separate table name ...