Home > Software engineering >  CombineLatest returns wrong value
CombineLatest returns wrong value

Time:12-17

I realized that the subscription returns a wrong value

// in ts file of a component
combineLatest([this.editSrv.getOrders(), this.route.queryParams]).subscribe(data => {
    this.orders = data[0];
    ...
})
 

with

// in editSrv
 getOrders(){
    // orders$: BehaviourSubject
    if(this.orders$.getValue().length > 0){
      // ordersSource = this.orders$.asObservable()
      return this.ordersSource$;
    }
    return this.http.get<any[]>("retrieve orders from api").pipe(
      map(orders => {
        this.orders$.next(orders);
        return orders;
      })
    )
  }

When I now remove an order with the following function in the component

removeOrder(order){
    let foundOrder = this.orders.find(o => o.id == order.id);
    if(foundOrder){
        const index = this.orders.indexOf(foundOrder);
        this.orders.splice(index,1);
    }
}

and change the queryParams of the current route with this function

cancel(){
    this.router.navigate([]); 
}

the combineLatestfrom above is triggered but this.editSrv.getOrders() returns the orders without the removed order although I did not call next but why does getOrders() returns now all the orders except the order I removed within the component without calling next? Shouldn't the source be left untouched?

CodePudding user response:

I think you need to do this.orders$.next(foundOrder); after removing item;

if(foundOrder){
    const index = this.orders.indexOf(foundOrder);
    this.orders.splice(index,1);
    this.orders$.next(foundOrder);
}

and then I believe you won't need combineLatest anymore

  • Related