Creating a promise with subscribe in Angular 2 using the http.post method

I am currently working on creating a function that returns a Promise in the code snippet below (someprovider.ts)

postToPaymentApi(url:string, data:string, options:RequestOptions, order:Order):Promise<any>{
let result =  this.http.post(url, data, options).map(res => res.json())
  .subscribe(data => {
    // all my logic here!
    });
  }, error => {
    console.log(error)
  })

  return new Promise((resolve)=>{
    resolve(result)
  })

}

The issue arises when I call this function and do not receive the expected data. This is because the post request takes some time to complete and the promise resolves before that.

this.postToPaymentApi(url, data, options, order).then(data => {
    console.log(data);
  })

Can anyone help me identify what mistake I am making?

Answer №1

To successfully create a function that returns a promise, you should adhere to the following structure:

sendToAPI(url:string, data:string, params:RequestOptions, orderInfo:Order):Promise<any >{
   return new Promise((resolve, reject) => {
          this.http.post(url, data, params)
           .map(res => res.json())
           .subscribe(responseData => {
             resolve(responseData);
            }
           }, errorResponse => {
             console.log(errorResponse)
             reject({error: errorResponse});
           });
        });
}

Answer №2

Andre, if you want to convert the observable returned by .map() into a promise, you should utilize the toPromise operator. Make sure to return the result of this operator.

return http.post(...).map(...).toPromise()

With the proper promise returned, the calling code can now handle it accordingly:

postToPaymentApi(...).then(
    data => console.log(data)
)

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

I am encountering an issue where the threejs lighting effects, such as pointlight and ambientlight, are not functioning properly in version "three": "^0.164.1". What could be causing this problem

Embarking on my first threejs project using vite and the threejs library I implemented the following light functions in my JS file: // Emit light evenly in all directions from a specific point in space const pointLight = new Three.PointLight(0xff0000, 1, ...

What causes variations in the values returned by outerWidth on different websites?

Curiously, I have noticed that window.outerWidth returns a larger value at Stackoverflow.com compared to other websites in my browser. This behavior seems to be unique to Firefox and Stackoverflow. But shouldn't it be consistent across all websites? ...

Using Node.js and Typescript to implement a chain of logical AND operations with an array of any length

Setting: I am developing a versatile function that determines a boolean outcome based on logical AND operations. However, the function is designed to handle various types of objects and arrays, each requiring different conditions. Currently, my code look ...

Utilizing Google Geochart to map out urban areas within a designated region

I am facing an issue with plotting markers in a specific city using Google Geochart when the region is set to only display that state, not the entire US. Although I can successfully plot the specific state, I encounter problems when trying to add markers. ...

Having issues with the ASP.NET Web Api and Angular Frontend integration

I recently tried following a guide on ASP.NET Web Api and Angular, which you can find here. While I followed the steps closely, the only difference was that I used .NET version 7 instead of version 6 for the Web Api. When I ran the project for the first ti ...

Issue Updating Angular 13 formGroup with API Response

Currently, I am working on creating a form to input data and save it for later editing. While most of the functionality is working smoothly, I am experiencing issues with using [(ngModel)] specifically for multiple entries in the list of cars. Additionally ...

Using Jquery Ajax to Send Data with ASP Core ActionResult

Is there a way to successfully submit a form data using Jquery Ajax in Asp Core? AJAX CODE if (contactForm.valid() == true) { var formData = new FormData(); formData.append("Name", contactForm.find("input[name='Name']& ...

Initiating an AJAX request to communicate with a Node.js server

Recently, I started exploring NodeJS and decided to utilize the npm spotcrime package for retrieving crime data based on user input location through an ajax call triggered by a button click. The npm documentation provides the following code snippet for usi ...

Combining JSON fields and searching based on the combined value within MarkLogic

In the JSON format provided below, I have stored a person's first name and last name along with their nickname. { "Person": { "Records": [ { "nameType": "Primary", "firstName": "Sagar", "lastName" ...

Is there a way to simultaneously filter by two attributes using mat-select-filter in Angular?

I have integrated the mat-select-filter library in my Angular project, but I am facing an issue with the displayMember filter. Currently, it only filters by code, but I would like it to also filter by name simultaneously. Is there a way to achieve this u ...

Tips for invoking TypeScript code from Rust WebAssembly

Currently, I am considering transitioning a slow TypeScript library (jackson-js) to WASM using rust. This particular library has various dependencies, like reflect-metadata for example. These dependencies are already created and accessible on npmjs. The ...

How to Handle Overlapping Divs in HTML?

I have a sizable container div with various dynamic divs nested inside. These child divs are often padded to the left and contained within another div that is also padded on the left. My goal is to make the overall container div (which has a border) adju ...

Invoking a Typescript function from the Highcharts load event

Struggling to call the TypeScript function openDialog() from the events.load of Highcharts? Despite using arrow functions, you are running into issues. Take a look at the code snippet below: events: { load: () => { var chart : any = this; ...

When Firebase authentication signs out users who were previously authenticated, it results in them facing permission denied errors

1) User A visits my website, and A is successfully authenticated and can write to the firebase database through the web browser. 2) User B then visits my site, and after being authenticated, they are able to write to the firebase database via the browser. ...

Creating a slider plugin with Right-to-Left (RTL) support

Despite multiple requests being ignored by the developer to support RTL on PhotoSwipe, I have decided to take matters into my own hands. Reversing the array order was a simple task: self.items = !!(_options.rtl) ? _items = items.reverse() : _items = item ...

Critical section in Node.js - transferring data from frontend to JSON file

I have a question about synchronizing requests for writing data to a file from multiple users simultaneously. In Java, there is the synchronized keyword but I am unsure how it can be achieved in Node.js. app.post("/register", function(req, res){ f ...

Tips for showcasing data in the autocomplete feature

I have implemented the following code to show values: function retrieveValues(input) { var xhttp; if (input.length == 0) { document.getElementById("output").innerHTML = ""; return; } xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = functi ...

Unexpected behavior of Ajax response from PHP

When I click the button, I am calling the JavaScript function cancelAppointment. I can see that the function is running properly because the first alert is displayed. I have tried following various guides to make this work, but so far I have not had any s ...

Data from graphql is not being received in Next.js

I decided to replicate reddit using Next.js and incorporating stepzen for graphql integration. I have successfully directed it to a specific page based on the slug, but unfortunately, I am facing an issue with retrieving the post information. import { use ...

JavaScript validation code for verifying hostnames with a specified domain name

I need a customized validation check for my order form where users are asked to enter their server hostname. The challenge is that I'm using WHMCS with encrypted PHP code and IonCube loaders, making it difficult to add this check. Users can input any ...