Tips for saving the generated POST request ID for future use in another function

I am facing a challenge where I want to use the ID of a newly created Order as the OrderId for an OrderLine that needs to be created immediately after.

After creating the Order, if I log the orderId INSIDE THE SUBSCRIBE METHOD, it shows the correct value.

However, once the subscribe function is completed, the value reverts back to undefined.

The checkout process is functioning correctly.

 async checkout() {
    // Perform PayPal or Stripe checkout process
    this.createOrder();
    let alert = await this.alertCtrl.create({
      header: 'Thanks for your Order!',
      message: 'We will deliver your food as soon as possible',
      buttons: ['OK']
    });
    alert.present().then(() => {
      this.modalCtrl.dismiss();
    });   

    this.cart = []; 
     
    this.cartService.removeCartItemCount(); 
  }

The createOrder function is working fine (except for storing the orderId for future use).

createOrder(){
    const orderForCreation: OrderForCreation = {
      orderDateCreated: this.currentDate,
      orderDateCompleted: this.currentDate,
      qrCodeSeatingIdFk: 2
    };

    const apiUrlOrder = 'api/order';
    
    this.repository.create(apiUrlOrder,orderForCreation)
      .subscribe( res =>{
        this.createdOrderId = res.orderId; 
        console.log(this.createdOrderId) //this works    
        this.createOrderLine(this.createdOrderId) //this does not work   
    }); 
    console.log(this.createdOrderId); //this does not
  }

The createOrderLine function is also working but I am unsure how to set the orderId to the correct ID.

 createOrderLine(id){
    const apiUrlOLine = 'api/orderLine';
    for (let i = 0; i< this.cart.length; i++){
      const orderLineForCreation: OrderLineForCreation = {
        orderIdFk : id, //This isn't updating
      itemQty : this.cart[i].menuItemAmount,
      itemComments : "item comment",
      menuItemIdFk : this.cart[i].menuItemId,
      specialIdFk : 1,
      employeeIdFk : 1,
      }
      

      console.log('orderline not created');

      this.repository.create(apiUrlOLine, orderLineForCreation)
        .subscribe(res => {
          this.createdOrderLineId = res.orderLineId;
          console.log('OrderLineCreated');
        });
    }
  }

If anyone has suggestions on how to resolve this issue, I would greatly appreciate it.

Answer №1

When subscribing to the this.repository.create, keep in mind that it is an asynchronous operation. This means you cannot predict when the subscription will be completed, leading to the possibility of the log being called before it finishes.

this.createOrderLine(this.createdOrderId) //this does not work  

Are you indicating that the method is not being called, or that the this.createdOrderId is undefined?

If you want the orderId to be returned from the createOrder function, you need to ensure that it returns an Observable and then subscribe to it during checkout process.

In the createOrder function:

return this.repository.create(apiUrlOrder,orderForCreation)
  .pipe(
    tap(res => this.createOrderLine(res.orderId))
    map(res => res.orderId)
  );

In the checkout process:

this.createOrder().subscribe(orderId => {
  //perform necessary actions like displaying alert
});

An issue may exist in your current implementation where this.createOrderLine is invoked, but the response from createOrder is returned before all items are created. To address this, you could gather all items as observables in an array, use forkJoin, and then subscribe to the combined result.

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

Discover the power of working with asynchronous values in objects using the latest @if syntax in Angular 17

Previously, we were able to chain multiple async operations using *ngIf directives in Angular. This allowed us to avoid repeating the async pipe in the template and instead reuse them as a single subscription. With the introduction of the new @if syntax in ...

Ways to display an icon with an underline effect upon hovering over text

I have implemented a CSS effect where hovering over text creates an underline that expands and contracts in size. However, I now want to display an icon alongside the text that appears and disappears along with the underline effect. When I try using displa ...

Experiencing a 404 error while attempting to revoke access token using Google OAuth2 revoke endpoint

Using angularx-social-login for user authentication via Google. The token retrieval process looks like this: https://accounts.google.com/o/oauth2/iframerpc?action=issueToken&response_type=token%20id_token&login_hint=LOGIN_HINT&client_id=CLIEN ...

Using ReactJS with Typescript: attempting to interpret a value as a type error is encountered (TS2749)

Currently, I am working on coding a ReactJS class using Typescript and Material-ui in a .tsx file. In one of the custom components that I have created, I need to establish a reference to another component used within this custom component. export class My ...

Angular: Dynamically changing checkbox's status from parent

I'm in the process of developing a switcher component that can be reused. The key requirement is that the state of the switch should only change after an API call is made at the parent component level. If the API call is successful, then the state cha ...

The state of dynamically created Angular components is not being preserved

My current task involves dynamically creating multiple components to be placed in a table. The code successfully achieves this objective, but the state seems to be getting jumbled up at the level of the dynamically generated components. When a component is ...

When using an Angular bootstrap Popover, I noticed that it tends to close when hovering outside of it. It would be more convenient if the Popover stayed open as

I am currently utilizing the PopoverModule feature from ng-bootstrap. One of the options available is to display the popup when hovering over it. Inside my popover, I have included an href link that directs to another page. The issue I am facing is that wh ...

Unable to submit form at the moment

I am currently exploring PHP/POST methods to assist me in my day-to-day job as a Web Developer. Despite following online tutorials, when I attempt to submit the form, the page redirects to bagelBack.php, but displays a blank page and does not submit the tw ...

How come Typescript claims that X could potentially be undefined within useMemo, even though it has already been defined and cannot be undefined at this stage

I am facing an issue with the following code snippet: const productsWithAddonPrice = useMemo(() => { const addonsPrice = addonsSelected .map(id => { if (addons === undefined) { return 0} return addons.find(addon => addo ...

In TypeScript, use a Record<string, any> to convert to {name: string}

I have developed a custom react hook to handle API calls: const useFetch: (string) => Record<string, any> | null = (path: string) => { const [data, setData] = useState<Record<string, any> | null>(null); var requestOptions: Requ ...

New feature: Mat select placeholder color change without needing required field validation

When the page initially loads, all controls (such as city, state, etc.) have white text color as shown in Image 1. I want to change the text color to red for all controls upon loading the page, resulting in a look similar to the image below. In the sectio ...

Steps for updating the clientId and authority values in MSAL configuration after they have already been read

Currently, I am utilizing Azure AD B2C for a multi-tenant application. The user starts by inputting their email, followed by selecting an option from a drop-down list populated based on the tenant they are associated with (tenant1, tenant2, tenant3). If th ...

The synergy between ternary operators and Vue filters

Recently, I came across a peculiar issue while working with Vue. Take a look at the code snippet from vue.html: <label :text= "$props.information ? (($props.information.primary || $props.information.secondary) | myFilter) : `No info`"> </lab ...

Error message occurs during compilation of basic Vue file in Webpack

When I execute webpack watch in the VS2017 task runner, it displays the following error: ERROR in ./wwwroot/js/src/App.vue Module build failed: SyntaxError: Unexpected token { at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:373:25) ...

Pull in a component from another repository

I recently established a repository in bitbucket named "angular-lister". The layout of the repository can be viewed . Subsequently, I created another repository with a similar structure, although I cannot display an image here. In this secondary repositor ...

As a quirk of TypeScript, it does not allow for returning a Tuple directly and instead interprets it as an Array

I need assistance with adding type-safe return to a general function created by a previous developer. Here is the current syntax: export function to(promise:Promise<any>) { return promise .then(data => [null, data]) .catch(err => [ ...

Can you please verify the most recent updates for Bootstrap and Syncfusion in my Angular project?

Could someone help me figure out when the bootstrap and syncfusion libraries were last updated in my Angular project? I'm having difficulty finding this information. ...

What is the best way to retrieve entire (selected) objects from a multiselect feature in Angular?

I'm facing an issue with extracting entire objects from a multiselect dropdown that I have included in my angular template. Although I am able to successfully retrieve IDs, I am struggling to fetch the complete object. Instead, in the console, it dis ...

Sharing API data between components in Angular 5

Summary: I'm trying to retrieve data from an input field in a component form, then compare it using API services. After that, I want to take the value from the "correo" field in the form and pass it to another component. In this other component, I aim ...

Discover the power of Angular's directive microsyntax when working with cdkConnectedOverlays

The Angular docs mention a microsyntax that can be utilized with structural directives. I currently have functional code using the cdkConnectedOverlay directive in its 'long hand' form: <ng-template cdkConnectedOverlay [cdkConnec ...