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

Having trouble with an unusual Protractor issue: Jasmine test cases not working properly?

UPDATE: The question was modified on September 17, 2018 Whenever my test case passes, everything looks good on the output screen as it displays 'passed'. However, when it fails, I encounter a lengthy red error message that seems to indicate an i ...

Guide to creating a one-to-one object literal map with a different value type using a function return without explicitly defining the return type

At the moment, I have successfully managed to combine the keys and values of each object literal that is passed into a function. For example: interface StaticClass<T = any> { new (...args: any[]): T } type RecordOfStaticClasses = Record<string, ...

What exactly happens behind the scenes when an API request is cancelled in an ASP .NET Core API?

Let's consider a scenario where we have a straightforward endpoint: [HttpGet] public async Task<ActionResult<string>> Get(CancellationToken cancellationToken) { // some logic here... } Now, imagine I make an HTTP request usi ...

Merging all Angular 2 project files into a single app.js document

I've scoured the depths of the internet for an answer to this burning question: How can I merge all my Angular 2 code, along with its dependencies, into a single file? Although this query has been posed countless times before, I bring a fresh perspect ...

angular2 variable turns null during post request, synchronization breakdown

Currently, I am in the process of developing an ecommerce web application using Angular2 and have encountered a issue with saving ordered information in session. addToCart(productId:string,noOfItems:number):void{ let itemCounts; let selectedItems= ...

Tips for embedding different pages within a single page using Angular 5

My project consists of 4 pages. [ { path: 'page1', component: Page1Component }, { path: 'page2', component: Page2Component }, { path: 'page3', component: Page3Component }, { path: 'page4', component: Page4Co ...

combineLatest will trigger only for the initial event

I am looking to combine 3 events and trigger a service call when any of them are fired. Currently, I am using the combineLatest method, but it seems to only work when the first event is triggered by filterChanged. The issue here is that filterChanged is a ...

TypeScript's type casting will fail if one mandatory interface property is missing while an additional property is present

While running tsc locally on an example file named example.ts, I encountered some unexpected behavior. In particular, when I created the object onePropMissing and omitted the property c which is not optional according to the interface definition, I did not ...

Minimum width of Angular Material's mat-menu

I am looking to create a compact Material mat-menu using Angular 15. Below is the code I have: <mat-menu #flagMenu="matMenu"> <button mat-menu-item> <img src="assets/flags/en.png" class="flag"/> ...

Filtering without specifying a data type and (with any luck) converting

Upon defining the function below: const filterAndCast = <T, U>( items: T[], predicate: Predicate<T>, cast: (x: T) => U, ) => items .reduce( (p, c) => [ ...p, ...(predicate(c) ? [cast(c)] ...

Exploring the methods for monitoring multiple UDP ports on a single address in Node.js within a single process

I am currently working on developing a Node.js application to manage a small drone. The SDK provides the following instructions: To establish a connection between the Tello and a PC, Mac, or mobile device, use Wi-Fi. Sending Commands & Receiving Responses ...

Obtain the ViewContainerRef object from the Component

Looking to create nested components in Angular 4? This is the Chooser Component import {InputComponent} from './input/input.component' import {BlockComponent} from './block/block.component' export const FormChooser = { Block: Block ...

Tips for calculating the total of keyup elements in an Angular application

There are "N" inputs in a formgroup that need to be summed: <input (keyup)="sum($event)" type="text" name="estoque_variacao{{i}}" class="form-control" id="estoque_variacao{{i}}" formControlName="estoque_variacao"> This is the Typescript code: sum( ...

How to load several stylesheets for a component in Angular 2

Struggling with my angular2 application, I encountered an issue when attempting to load multiple stylesheets for the same component. Below is a snippet of the code: import { Component } from '@angular/core'; @Component({ selector: 'my-tag& ...

TS - decorator relies on another irrespective of their position within the class

Is it possible to consistently run function decorator @A before @B, regardless of their position within the class? class Example { @A() public method1(): void { ... } @B() public method2(): void { ... } @A() public method3(): void { ... } } In the sc ...

Unexpected errors are encountered when using ng serve

When I run the ng serve command, unexpected errors are occurring on my system. The errors include: PS C:\Users\SAYED-SADAT\Desktop\data\coding\itsm-frontend\itsm-frontend> ng serveYour global Angular CLI version (13.0 ...

Exploring the Power of Map with Angular 6 HttpClient

My goal is to enhance my learning by fetching data from a mock JSON API and adding "hey" to all titles before returning an Observable. Currently, I am able to display the data without any issues if I don't use the Map operator. However, when I do use ...

Directing non-www to www in Next.js has never been easier

Based on the information I've gathered, it seems that using www is more effective than not using it. I am interested in redirecting all non-www requests to www. I am considering adding this functionality either in the next.config.js file or, if that& ...

Creating typed props is important when utilizing the Material UI makeStyles function

Currently, I'm in the process of transitioning some of my React components to the latest makeStyles/useStyles hook API from Material UI. As far as I know, I can still accept classes as a prop from parent components by passing the props to useStyles: ...

Utilizing the JavaScript Array.find() method to ensure accurate arithmetic calculations within an array of objects

I have a simple commission calculation method that I need help with. I am trying to use the Array.find method to return the calculated result from the percents array. The issue arises when I input a price of 30, as it calculates based on the previous objec ...