Unable to send a httpClient request when invoked prior to unloading

Having an issue with calling a function that listens to the event onBeforeUnload() and trying to post data using an httpClient request. However, the request is not being sent correctly. Here's the code snippet:

  @HostListener('window:beforeunload', ['$event'])
  onBeforeUnload(): void {
     this._httpClient.post(`${localhost:8080/apiRest}`, infoIWantToSent).subscribe();
  }

Seeking guidance on whether this approach is correct. Any help would be appreciated. Thank you.

Answer №1

What is the purpose of not utilizing ngOnDestroy?

export class UpdatedComponent implements OnDestroy{
    ngOnDestroy() {
            this._httpClient.post(${localhost:8080/apiRest}, dataToSend).subscribe();
    }
}

Answer №2

Appreciate your response. I encountered an issue where the OnDestroy method wasn't being called in my scenario. However, I managed to find a solution by implementing the following:

@HostListener('window:beforeunload', ['$event'])
  onBeforeUnload(): void { 
    const xhr = new XMLHttpRequest();
    xhr.open('POST',
${localhost:8080/apiRest
, false);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('Authorization', 'Bearer ' + token);
    return  xhr.send(JSON.stringify(infoIWantToSent));
  }
Seems to be effective. The token referenced here is the authentication token for my application.

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

Ways to programmatically move from one step to another in ngx-admin nebular stepper

Currently utilizing the nebular ngx-admin template, I have encountered some challenges with the nebular stepper. Within one component, I have implemented four steps. In the component file, I have utilized Nebular API's methods: @ViewChild("stepp ...

Encapsulating functions with multiple definitions in Typescript

Struggling with wrapping a function that can have multiple return types based on input parameters in Typescript. Imagine wanting a function to return ReturnA for VariantEnum.a and ReturnB for VariantEnum.b. Consider this implementation of sampleFunction: ...

TypeScript declaration specifying a NodeJS module that exports a class definition

Currently grappling with creating a TypeScript declaration file for HtmlWebpackPlugin, but struggling to make it functional. The default export of HtmlWebpackPlugin is the constructor for the class HtmlWebpackPlugin, which I aim to use as shown below: so ...

The Vue component's TypeScript object prop type does not match the expected value

Having trouble with the type of Object properties in Vue Single File Components using TypeScript (created with Vue CLI 3)? Check out the example below to see the issue. The type of this.product is currently showing as (() => any) | ComputedOptions<a ...

Angular 2 update function in the MEAN Stack is not functioning as expected

I'm encountering a strange error that I can't seem to figure out. I've selected PUT on my postman and using route.put. Here's the error message I'm getting in Postman: Image link -> https://ibb.co/dzvAKc Looking at all the mus ...

Generate a nested array of objects by recursively looping through an array of objects

Imagine I have an array of objects structured like this: myArr = [ { "id": "aaa.bbb" }, { "id": "aaa.ccc" }, { "id": "111.222" }, { "id": "111.333" }, ] I aim t ...

(Angular4 / MEAN) Making a Request to Local API Yields an Empty Response Body

I'm attempting to send data to an Items API, like this: "data": { "title": "stack", "notes": "asdsad", "time": "19:02", "meridian": "PM", "type": "Education", "_id": "5a2f02d3bba3640337bc92c9", ...

Viewing the photo container before uploading while having text overlap

I'm encountering an issue where the image previews are overlapping with the text in another div. Here are the screenshots: the first one shows how it looks before the preview, and the second one shows what happens when images are added: https://i.sst ...

Mastering the process of importing AngularJS submodules in TypeScript

Currently, I am in the process of structuring an AngularJS (Angular 1) project using TypeScript. To compile TypeScript & ES6 to JavaScript, I have set up webpack. In my webpack configuration, I only compile the "app.ts" file and any other files it imports ...

Display the specified [object][object] in the header of Angular PrimeNG Multiselect component

When using angular primeng multiselect, it sometimes displays [object][object] in the header instead of the optional label when in edit/on focus state. Here is my code snippet <p-multiSelect(onFocus)="insertOptions(row,itemProperty.options,itemPropert ...

Find with user-friendly input/label removal function (Ionic 2)

I have embarked on creating a recipe application where users can search for recipes by ingredients. I want to enhance the functionality of the search feature so that when users press the spacebar to enter the next input, it appears as a label below with an ...

Leverage AngularCLI to create components for projects containing multiple apps

In my current project setup, the configuration in my .angular-cli.json file is structured as follows: { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "project": { "name": "suman-chrome-extension" }, "apps": [ { "r ...

GUIDE: Creating an Angular library comprised of standalone feature sub-libraries

Currently in the process of developing a custom Angular library using Angular v 8.1.0, I am interested in figuring out how to organize it into different sub-libraries. For instance, the Angular core is divided into separate parts like: @angular/common @ ...

When accessing the innerHTML and outerHTML properties on an HTMLElement, they may return undefined without triggering

Task: My goal is to take an HTML string, make changes to certain attributes of image tags within it, and then return the modified HTML string. The function I have developed follows these steps: private resolveImagesInHTML (body: string): string { le ...

Issues arise when trying to type ChangeEvent in React using Typescript

After spending some time learning React with TypeScript, I encountered a problem. The prop onChangeHandler in my code takes a function to modify properties in formik values. <Formik<FormModel> initialValues={{ favorite: ...

What could be causing the index.tsx file to not locate the Clock Module?

Here is the code snippet I have in my index.tsx file. import Clock from "./utility/clock"; And this is my tsconfig setup. { "compilerOptions": { "sourceMap": true, "noImplicitAny": true, "module": "es6", "target": "es5", ...

What are the steps to fix errors when deploying a MEAN stack application on Heroku?

Upon building my Angular app with a Node.js API and deploying it on Heroku, I encountered an error. Despite this, the app runs smoothly with no errors when tested on my local server. Below are the logs from Heroku: C:\Users\PC>heroku logs -a= ...

Having trouble retrieving data from a JSON file within an Angular application when utilizing Angular services

This JSON file contains information about various moods and music playlists. {mood: [ { "id":"1", "text": "Annoyed", "cols": 1, "rows": 2, "color": "lightgree ...

Rendering Information in Angular 4 Through Rest API

Encountering issues displaying data from my local express.js REST API, organized as follows: people: [{ surname: 'testsurname', name: 'testname', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemai ...

Demystifying the Mechanics of RxJS Subscriptions during an HTTP Request

export class VendorHttpService { result = '0'; constructor(private http: HttpClient, private global: GlobalService) { } getProfileStatus(uid: String): string { this.http.get(this.global.getUrl()+"/vendor/profile-status/"+uid) ...