The attempt to create a new instance of 'XMLHttpRequest' failed because the constructor requires the 'new' operator to be used. This DOM object cannot be invoked as a function

export default class CustomPromise extends XMLHttpRequest {
    constructor(url: string, type: string) {
        super();
        config.url = url;
        config.requestType = type;
    }
}

In this code snippet, a custom promise class is created by extending the XMLHttpRequest. An instance of this class is then attempted to be created as shown below.

let customProm = new CustomPromise('api/200', 'get');

However, upon calling the super method, the following error was encountered:

Failed to construct 'XMLHttpRequest': Please use the 'new' operator, this DOM object constructor cannot be called as a function

Answer №1

It seems like the issue arises because the XMLHttpRequest object is a hosted object, and sometimes it behaves erratically when extended.

Fortunately, this behavior changes when you extend it using ES6 classes.
After compiling the following code:

class RequestPromise extends XMLHttpRequest {
    constructor() {
        super();
    }
}

When transpiled to ES5, it becomes:

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var RequestPromise = (function (_super) {
    __extends(RequestPromise, _super);
    function RequestPromise() {
        _super.call(this);
    }
    return RequestPromise;
}(XMLHttpRequest));

However, if you compile it with target set to ES6, the class remains unchanged:

class RequestPromise extends XMLHttpRequest {
    constructor() {
        super();
    }
}

If you give it a try, it should function properly without any issues.

Answer №2

Using XMLHttpRequest simplifies the process of sending HTTP requests. With just a few lines of code, you can create an instance of the object, specify a URL, and send the request.

var request = new XMLHttpRequest();

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

Double Calling of Angular Subscription

I am currently working with a series of observables that operate in the following sequence: getStyles() --> getPrices() Whenever a config.id is present in the configs array, getStyles() retrieves a style Object for it. This style Object is then passed ...

Steps to showcase a visual element using an interceptor

I am in the process of building a web application with Angular 6. One key aspect of this project is implementing an interceptor service that utilizes the interface HttpInterceptor to intercept specific types of HTTP requests. So far, the interceptor class ...

Updating TypeScript interface based on a generic value

I am currently working on modifying a TypeScript interface based on specific keys found in an object. The object I receive from GraphQL has the following structure: { "vamm": { "__typename": "Vamm", "stats" ...

What can be done to prevent the angular material select from overflowing the screen?

I have integrated an Angular Material Select component into my application, which can be found here: https://material.angular.io/components/select/overview. The issue I am facing is that when the select element is positioned near the bottom of the screen a ...

Using TypeScript to type styled-system props

Currently, I am utilizing styled-system and one of the main features of this library is its shorthand props that allow for simple and quick theming. Although I have streamlined my component, a significant aspect lies here: import React from 'react&a ...

Transferring data between arrays in TypeScript depending on a specified condition

I am looking to transfer all data from one array to another in TypeScript based on a certain condition. array: any = [ { Hostname: 'CBA', Certificate_Expiry_Date: ...

The type 'Store<unknown, AnyAction>' is lacking the properties: dispatch, getState, subscribe, and replaceReducer

I have configured the redux store in a public library as follows: import { configureStore } from '@reduxjs/toolkit'; import rootReducer from '@/common/combineReducer'; import { createLogger } from 'redux-logger'; import thunk ...

Error in Angular2: The provided parameters do not match any of the available function signatures

I have implemented logic in the code snippet below to dynamically adjust rows and columns based on my specific business requirements. However, when I include this code in my Angular2 TypeScript file, I encounter an error stating that the supplied paramet ...

React Hook: Child Component's onComplete Callback Cannot Call Parent Component's Dispatch

I've attempted multiple solutions to address this issue, but none have proven successful. In my scenario, a third-party library makes an asynchronous call to load content for rendering in the DOM. To integrate this functionality, I have a component ...

Reset Angular's virtual scroll to the beginning of the list

Within my Angular application, I am utilizing the Virtual Scroll feature from the Angular cdk. Here is a snippet of my Component's template: <cdk-virtual-scroll-viewport itemSize="50" class="example-viewport"> <div *cdkVirtualFor="let ite ...

This error occurs when trying to assign a value to a property of a variable that is currently undefined

Having some issues with assigning the latitude and longitude values to a variable in my code. I am able to retrieve them correctly, but when trying to use them in another method (onUpload()), I am facing some errors. export class latlonComponent implement ...

Creating a JSON file using an object to send requests in Angular

In my Angular 7 project, I am trying to send a multipart request to the server that includes a file (document_example.pdf) and a json file containing a data object (data_object_example.json). The content of data_object_example.json is as follows: { " ...

Tips for patiently awaiting data before constructing an object

Currently, I am uploading image files to a server and returning the download URL and upload percentage with my upload method. Looking ahead, I plan to enhance this functionality to allow for the upload of multiple images using the same component. The goal ...

When utilizing <number | null> or <number | undefined> within computed() or signals(), it may not function properly if the value is 0

I've encountered an issue while implementing signals and computed in my new Angular project. There's a computed value that holds an id, which is initially not set and will be assigned by user interaction. To handle this initial state, I attempte ...

The functionality of an Angular application may be compromised if the necessary modules are not properly imported into

I've noticed some strange behavior in my code recently and I can't figure out where it's originating from. In an effort to clean up my codebase, I decided to create separate modules for each component and a routing module to manage all the r ...

Tips for utilizing the patchValue method within a dynamic FormArray in Angular

When working with the first case (check out the DEMO link), patchValue() function can easily manipulate the select drop-down menu in a reactive FormGroup(), where only FormControl() is used. However, in the second case, I need to achieve the same functiona ...

What is the best way to design functions that can return a combination of explicit types and implicit types?

When looking at the code provided below, function system(): ISavable & ISerializable { return { num: 1, // error! save() {}, load() {}, serialize() {}, deserialize() {}, } } interface ISavable { sa ...

What could be the reason for Jest running my TypeScript test twice and consistently failing one of the runs?

Currently, I am in the process of writing a test for a simple route within my API backend. This test is being written using Typescript and Jest, all within a docker container that I initiate using docker-compose. For my testing purposes, I have created a ...

Enabling or Disabling Inputs in Angular

I'm looking to customize my form behavior in a specific way - when I click on the modify button, I want only one line to be modified instead of all three. How can I achieve this? Images : edit save app.component.html : <table mat-table [dataSourc ...

Use RXJS to prevent having multiple nested subscriptions

I am looking to revamp the code snippet below: this.dataUserSubscription = this.store$.pipe(select(selectUser)).subscribe( user => { this.store$.pipe(select(selectUserData, {user}), take(1)) .subscribe(u ...