Refraining the XMLHttpRequest Function from Ceasing

One of the functionalities in my app involves uploading files using XHR. Users have the option to cancel the upload by clicking on a button.

If the user cancels the upload, the value of file.canceled is set to true. I'm constantly checking during the upload progress (onprogress event) to see if the upload has been canceled.

In case of cancellation, I trigger xhr.DONE. However, this action does not actually stop the upload process as intended.

Here's the code snippet: (I'm working with Angular 6 and using Typescript)

upload(f: ProductFile): Observable<ProductFile> {
    var file: ProductFile;
    this.store$.pipe(
        select(FilesSelectors.getFileById(f._id)),
    ).subscribe((file: ProductFile) => file = file)
    return new Observable((observer) => {
        let xhr = new XMLHttpRequest();
        let progress: number = 0;
        xhr.upload.onprogress = (event: ProgressEvent) => {
            if (event.lengthComputable) {
                progress = 100 * (event.loaded / event.total);
                this.store$.dispatch(new FilesActions.UploadProgress({
                    ...file, progress, uploaded: false, uploading: true,
                }));
            }
            if (file.canceled) {
                observer.error('canceled')
                observer.complete();
                xhr.DONE;
            }
        }
        xhr.responseType = 'json';
        xhr.open('POST', `${this.httpService.url}/files/upload`, true);
        xhr.setRequestHeader('Authorization', this.httpService.token);
        xhr.send(f.formData);
        xhr.onload = () => {
            const finishedFile: ProductFile = {
                ...f,
                url: xhr.response,
                uploaded: true,
                uploading: false,
                progress: 100,
            };
            observer.next(finishedFile);
            observer.complete();
            xhr.DONE;
        }
    });
}

My main objective is to properly abort the uploading process when the value of file.canceled is indeed true.

Answer №1

Consider utilizing the abort() function from the XMLHttpRequest module in place of using DONE.

Here's an example:

xhr.abort();

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

unable to utilize a tip with d3 version 5 in a TypeScript environment?

i'm facing an issue with the following code snippet: var tip = d3.tip() .attr('class', 'd3-tip') .attr('id', 'tooltip') .html(function(d) { return d; }) .direction('n ...

What is the procedure for incorporating JavaScript into my tic-tac-toe game's HTML and CSS?

I have created a simple Tic Tac Toe game using HTML and CSS. Although there is no embedded Javascript, I do reference a Javascript file for functionality. Can anyone provide me with the most straightforward Javascript code that will display an 'X&apos ...

I am having trouble getting Javascript to function properly on my local server while using Google App Engine

It's been a full week and I have scoured numerous Spanish and English forums... The issue I'm facing is that Javascript isn't functioning on my localhost when I launch my website from Google App Engine. If I manually copy all the HTML, CSS ...

Creating an interactive particle system with three.js, ready to be clicked on

As I embark on my coding journey and delve into three.js, I've been eager to create interactive geometries. After some searching, I stumbled upon a code snippet (the links don't open in the snippet for some reason): var container, stats; var c ...

Tips on personalizing rows in an xlsx spreadsheet prior to exporting

When I receive an array of objects (dicts) as input, it looks something like the example below. const data = [ { id: 1, serviceId: 1, title: "A", model: "A", }, { id: 1, serviceId: 1, title: "T", model: "b", ...

Spotfire: Changing a URL in an input field after it has been entered by the user

Currently, I am faced with a challenge related to importing a file in spotfire based on the path provided by the user. To accomplish this, I am utilizing a data function written in R script. In R, it is essential to note that all "\" characters are n ...

Attempting to update a variable within a function results in an error message stating: "Attempting to use block-scoped variable '...' before it has been declared.ts(2448)"

I'm currently working on a typescript function that takes in a numeric array (defined as type: number[]) and computes the mean. I want to make sure that the function can handle cases where the input array includes some null values. To address this, I ...

Angular Material autocomplete options are obscured by browser autofill suggestions

I am facing a challenge in Angular Material where the material autocomplete feature is functioning properly, however, the browser's autofill options are causing an overlap with the material autocomplete popup. Is there a way to disable autocomplete fo ...

Adjusting the input in a Textfield within React using Material UI

const [formData, setFormData] = useState({}); useEffect(() => { fetch("/formdata") .then((res) => res.json()) .then((data) => setFormData(data)); }, []); console.log("Form Data", formData); //Sorting by order let attr; ...

The boxslider feature in Jquery is malfunctioning on the website

I recently took on the task of updating and enhancing a friend's website , which was originally created by a web designer a couple of years ago. While I have been able to add photos, recipes, and make some CSS adjustments successfully, I am facing an ...

Need help addressing a sliding page issue in my Upwork clone script using JavaScript

For those familiar with Upwork's UI, you may have noticed a small feature I implemented. When a user clicks on a freelance job offer, another page opens from the left side using transform: translate(120%) to transform: translate(0). The issue arises ...

Problem with resizing the calendar dialog in PrimeNG's p-calendar component

When using the <p-calendar from PrimeNg, I encountered an issue regarding the size of the calendar. When I resize the navigator to 60%, the calendar is visible https://i.sstatic.net/AJ3dCtw8.png. However, when the zoom of the navigator is set to 100%, t ...

Display or conceal a Div element within a Web Application

I need to toggle the visibility of a label inside a div based on the value of another text box using JavaScript. The function is functioning properly, but in the ASP.NET code-behind, I am using a select case statement to set the visibility of the DIVid to ...

The React useEffect hook runs whenever there is a change in the state

Within my React component, I have the following code snippet (excluding the return statement for relevance): const App = () => { let webSocket = new WebSocket(WS_URL); const [image, setImage] = useState({}); const [bannerName, setBannerName] = use ...

The jquery datetimepicker function cannot be located or is not functioning as intended

<link href="css/bootstrap-datetimepicker.min.css" rel="stylesheet" /> <script src="Js/bootstrap-datetimepicker.min.js"></script> <script src="Js/bootstrap-datetimepicker.he.js"></script> ...

Use jQuery to dynamically assign a unique div id to a specific class element

<div class="leaflet-marker-icon"></div> <div class="leaflet-marker-icon"></div> <div class="leaflet-marker-icon"></div> <div class="leaflet-marker-icon"></div> The map generates these divs, all with the s ...

Exploring the wonders of jQuery JSON parsing

What is the best way to handle this json data using jQuery? DayEvents: [{ "0": "886", "event_id": "886", "1": "5029", "user_id": "5029", "2": "Professional", "user_type": "Professional", ... ...

Utilizing GeoLocation in JavaScript: Implementing a Wait for $.ajax Response

Whenever I make an AJAX POST request to my backend server, I aim to include the latitude and longitude obtained from the navigator. However, it seems like the request is being sent in the background without waiting for the navigator to complete its task. ...

Upgrading Angular causes issues with fileReplacements not functioning properly for assets

Since upgrading Angular, I have encountered an issue where fileReplacements no longer work with assets. Here is the code snippet that I am using: "fileReplacements": [ { "replace": "src/assets/scss/x.scss", ...

Utilizing ExpressJS to save uploaded files using the FileReader object from the front-end

Despite researching multiple posts on this topic, I am still unable to successfully upload a file after numerous adjustments. My React form includes a PDF file upload component which looks like this: <Input onChange={(e) => this.handleFileUpload(e) ...