0

In below code:

  1. http call gets multiple orderline's (items) IDs
  2. for each of those makes another http call and reserves them. I then need to redo the page with those showing up as reserved.

Whith numerous items, the last 3 lines would execute and reload the page before they actually got reserved in the BE so I added that 0.7 sec delay but that's not best practice and I can't figure out how to do it otherwise (switchMap? how)

   this.service.getOrderlineId(this.orderlineIds).subscribe((ids: Number[]) => {
      ids.forEach(id => {
        this.currentReservation = {
          orderline: id,
          company: this.currentUser.company_id,
          company_name: this.currentCompany.name,
          user: this.currentUser.user_id,
          delivery_address: this.currentCompany.address
        }
        this.service.createOrderLineReservation(this.currentReservation).subscribe(reservation => {

        })
      })
    })

    setTimeout(() => {                       
      this.clearGroups();
      this.prepareRow();
      this.prepareGroups();
    }, 700);

1 Answer 1

1

You could use Rxjs's pipe to manipulate the streams

this.service
  .getOrderlineId(this.orderlineIds)
  .pipe(
    map((ids: number[]) =>
        // Map the ids to an Observable list
      ids.map((id) =>
        this.service.createOrderLineReservation({
          orderline: id,
          company: this.currentUser.company_id,
          company_name: this.currentCompany.name,
          user: this.currentUser.user_id,
          delivery_address: this.currentCompany.address,
        })
      )
    ),
    switchMap((reservations$: Observable[]) => 
    // After all observables emit, emit values as an array
    zip(...reservations$))
  )
  .subscribe((reservations: Reservation[]) => {
      // You get an ordered list of reservations

      this.clearGroups();
      this.prepareRow();
      this.prepareGroups();
  });

ps: Don't use setTimout

Sign up to request clarification or add additional context in comments.

1 Comment

Deprecated in favor of static zip. Just import from 'rxjs' instead of from 'rxjs/operators'. rxjs-dev.firebaseapp.com/api/index/function/zip

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.