Encountering an ERROR of TypeError when attempting to access the property 'length'

I encountered the following error message:

ERROR TypeError: Cannot read property 'length' of undefined at eval (webpack-internal:///./node_modules/@angular/common/esm5/http.js:163) at Array.forEach () at HttpHeaders.lazyInit (webpack-internal:///./node_modules/@angular/common/esm5/http.js:157) at HttpHeaders.init (webpack-internal:///./node_modules/@angular/common/esm5/http.js:305) at HttpHeaders.forEach (webpack-internal:///./node_modules/@angular/common/esm5/http.js:408) at Observable.eval [as _subscribe] (webpack-internal:///./node_modules/@angular/common/esm5/http.js:2210) at Observable._trySubscribe (webpack-internal:///./node_modules/rxjs/_esm5/Observable.js:177) at Observable.subscribe (webpack-internal:///./node_modules/rxjs/_esm5/Observable.js:165) at subscribeToResult (webpack-internal:///./node_modules/rxjs/_esm5/util/subscribeToResult.js:32) at MergeMapSubscriber._innerSub (webpack-internal:///./node_modules/rxjs/_esm5/operators/mergeMap.js:143)

This error occurs when attempting to upload a file, despite not implementing the length() function anywhere in my code.

Here is the relevant HTML snippet:

<app-supervisor-header></app-supervisor-header>
<main>
  <div class="container">
      <div class="col-sm">
        <h3>Modifying exam: {{examen.naam}}</h3>
        <form #examUpdateForm="ngForm" (ngSubmit)="onSubmit(examUpdateForm)">
          <div class="row">
            <!-- Form fields omitted for brevity -->
          </div>
        </form>
      </div>
  </div>
</main>

The Component looks like this:

export class SupervisorExamenAanpassenComponent implements OnInit {
  @Input() examen: Examen = new Examen(null, '', '', null);
  id: number;

  constructor(private serv: ExamService, private route: ActivatedRoute) { }

  onSubmit(form) {
    this.serv.updateExamById(this.id, this.examen).subscribe();
  }

  fileChanged(e) {
    const reader = new FileReader();
    reader.onload = () => {
      this.examen.file = reader.result;
    };
    reader.readAsText(e.target.files[0]);
  }

  ngOnInit() {
    this.route.params.subscribe(params => this.id = params.id);
    this.serv.getExamById(this.id).subscribe((data) => this.examen = data);
  }

}

Upon attempting to submit again, I receive an error pointing to HTML line 6 which is:

<form #examUpdateForm="ngForm" (ngSubmit)="onSubmit(examUpdateForm)">

Additional information:

ExamService details:

@Injectable()
export class ExamService {
  examens: Examen[] = [];

  constructor(private http: HttpClient) {}

  // Implementation details omitted for clarity
}

Answer №1

Modify the http.put call in ExamService to exclude a certain parameter:

{headers: {'Content-Type': undefined}}

There is no need to specify Content-Type as it will be automatically set by Angular's HttpClient API.

Instead of using FileReader to convert the file's Blob content to plain text, simply store a reference to the File and append it along with its Name to FormData upon submission. For example:

// Component
private file: File = null;

fileChanged(e) {
    this.file = e.target.files[0]);
}

onSubmit(form) {
  this.serv.updateExamById(this.id, this.file).subscribe();
}

// Service
updateExamById(id, file: File) {
  const fd = new FormData();   
  fd.append('file', file, file.name);
  return this.http.put<Examen>(APIURL + '/update/' + id, fd);
}

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

The base URL specified in the tsconfig file is causing the absolute path to malfunction

Displayed below is the layout of my folders on the left, along with a metro error in the terminal and my tsconfig.json configuration with baseUrl set to './src'. Additionally, I have included screenshots of my app.ts and MainTabs.ts for further c ...

How can we design a return type for a function in Typescript that enforces the exact keys present in the input array K[] to be included in the Record?

I have a function that takes an array of Animals, and returns a map where the keys are the animals and the values are their fur colors: export enum Animals { CAT = 'CAT', DOG = 'DOG', SEAL_PUP = 'SEAL_PUP', } const furC ...

Error message encountered when trying to associate "can" with an ability instance within Types

Just copying example code from documentation import { createCanBoundTo } from '@casl/react'; import ability from './abilities'; export const Can = createCanBoundTo(ability); An error occurs on the last line: The exported variable & ...

When running a callback function, the "this" of an Angular 2 component becomes undefined

One issue I'm facing is with a component that fetches data from a RESTful endpoint using a service, which requires a callback function to be executed after fetching the data. The problem arises when attempting to use the callback function to append t ...

Dynamic form controls within Angular are constantly changing and adapting

On my preference screen, users can sign up for various services that are received from a service provider. The Json data structure looks something like this: [ { category : 'General', source : [ { name: 'ABC News', ...

Surprising Denials Following the Launch of Karma Using NgUpgrade

Currently in the process of implementing ngupgrade into our AngularJS application and consistently encountering unexpected rejection errors while Karma is initializing. The functionality of my app with ngupgrade is running smoothly, but the issue lies wit ...

Transform the appearance of Angular Material's table with a new design

Currently, I am working with Data-Table from angular material and I am looking to customize the table style to better suit my needs. https://i.sstatic.net/KyJm8.png I'm wondering how I can remove the border/frame from the table and eliminate the 3D ...

I am currently working to resolve this particular wildcard issue with the help of TypeScript

I've been working on solving the wildcard problem with TypeScript, but I'm running into issues with some of the test cases I've created. Here's a brief overview of how the code operates: A balanced string is one where each character ap ...

Variety of properties determined by a "type" prop, expanding variations based on a value from the interface

I am trying to enhance a type based on a value from the main interface. If the type == multiline, it will have a specific interface, and if the type == icon, it will have a different type. import React, { memo, useCallback, ReactNode } from 'react&apo ...

Using ngFor in Angular 2-5 without the need for a div container wrapping

Using ngFor in a div to display an object containing HTML from an array collection. However, I want the object with the HTML node (HTMLElement) to be displayed without being wrapped in a div as specified by the ngFor Directive. Below is my HTML code snipp ...

Guide to accessing a nested and potentially optional object property with a default value and specifying its data type

Just a simple query here... my goal is to extract data.user.roles, but there's a possibility that data may be empty. In such cases, I want an empty array as the output. Additionally, I need to specify the type of user - which in this instance is any. ...

Enhancing TypeScript type definitions for the Response.render() method in Express

Struggling with enhancing the type safety of my Express project by extending the Response.render function. import { Response } from "express"; import { Product } from "../models/Product.interface"; export interface ProductListResponse ...

Creating a component in Angular that utilizes multiple nested FormGroups

When attempting to nest multiple FormGroups, everything works smoothly if the template is not extracted into separate components. For instance, the following example functions as expected: Template <form [formGroup]="baseForm"> <div formGr ...

Create a dynamically updating list using React's TypeScript rendering at regular intervals

My goal is to create a game where objects fall from the top of the screen, and when clicked, they disappear and increase the score. However, I am facing an issue where the items are not visible on the screen. I have implemented the use of setInterval to d ...

When maxSelectedItems is configured for multiple items, prevent further typing in the input field

After the maximum number of items has been selected in a multi select with maxSelectedItems, users should not be able to input any more text into the select field. Visit this link for demos ...

Problem with organizing data by dates

My timers list looks like this: timer 1 => { startDate = 17/01/2019 11PM, endDate = 18/01/2019 9AM } timer 2 => { startDate = 18/01/2019 7AM, endDate = 18/01/2019 1PM } timer 3 => { startDate = 18/01/2019 12PM, endDate = 18/01/2019 10PM } time ...

Communication between components through a shared service

Imagine you find yourself in one component and need to trigger a method from another component. There are multiple ways to achieve this, which are explained in more detail on this page. Here, I will demonstrate the simplest possible example of how to make ...

Unable to reach the margin-left properties of the elements

I am facing an issue in accessing the current margin-left CSS property of the class .circle in the code snippet below. A demonstration of this problem can be found on a website called PLUNKr. The reason I need to access this property is because I have to ...

Creating a Record instance consisting of a specific key and its corresponding value

Sorry for the complexity, I've struggled to simplify this further. Feel free to update the question title for more specificity. I aim to define a foundational data type structure: type AbstractBaseTypes = { [key: string]: { inputTypes ...

What is the best way to utilize a tsconfig "alias path" to import an @ngModule along with other definitions?

Repository Link: https://github.com/andreElrico/mono-repo-test Stackblitz Example: https://stackblitz.com/github/andreElrico/mono-repo-test (noop; only to navigate smoothly) Assume the structure below: root/ ├── projects/ │ ├── app1 │ ...