Sergej Bjakow
Sergej Bjakow

Reputation: 83

Observable not updated IF empty

I came across this strange behavior by the rxjs-"filter". Environment: SAP ComposableStorefront / Spartacus "~2211.21.0" angular 17.2.0

I'M on a product Detail Page and apply a filter on my Observable like this:

  name$: Observable<Product> = this.currentProductService.getProduct().pipe(
    filter((p: Product) => p.hasFlag)
  );

And render it just like this:

<div *ngIf="name$ | async as name">
  <h2>{{name}}</h2>
</div>

This works fine, but as soon as I navigate to a different DetailPage using a direct router Link, the Value stays the same IF the filter has returns an empty value.

IF the filter returns no values because p.hasFlag==false I expect No Rendering of "name" at all, but instead the the old value remains and stays for the new view. If I reload the page there is no value for that product as expected, but If I stay in app context and have received a value once, in that component, the value simply does not UPDATE, if a newly triggered Filter returns empty.

Is this a behaviour that makes sense?

I tried to play around with ChangeDetection, but that didn't help.

Upvotes: 1

Views: 59

Answers (1)

Tortila
Tortila

Reputation: 578

It works as intended. Look at the diagram of filter operator.

One of possible solutions is to use map operator:

name$: Observable<Product | null> = this.currentProductService.getProduct().pipe(
  map((p: Product) => p.hasFlag ? p : null)
);

Upvotes: 1

Related Questions