0

I'm trying to refactor a get http request. The code that I'm using now is getting the data from service and in the subscribe method also changing a boolean flag

 this.eventsService.getEvents(this.pageSize, this.currentPage).subscribe(
  (data) => {
    this.busy = false
    this.events = data.events
  }
);

I've refactor to use Observable on my view, and this code looks this way now, component code:

const $results = this.eventsService.getEvents(this.pageSize, this.currentPage);
this.$events = $results.pipe(tap(() => { this.busy = false } ), map(data => data.events));

view code (nativescript) :

<ListView *ngIf="!busy" [items]="$events | async" ></ListView>

it does provide proper content in the view but the busy flag is not changed in the tap operator. Is it feasible to somehow change boolean in the pipe() ?

9
  • Where is the subscribe in the refactored code? I'm not sure about the context of this code. Is it in a method? Should it be this.$results? Commented Jul 21, 2021 at 20:16
  • I'm using async pipe in the view file Commented Jul 21, 2021 at 20:18
  • With which stream? $results or $events? Commented Jul 21, 2021 at 20:19
  • $events, I've added one line from my view in the description Commented Jul 21, 2021 at 20:22
  • If it's displaying the proper content in the view, then busy must be false? (Your refactored code looks basically OK, so wondering if there is something else amiss?) Commented Jul 21, 2021 at 20:23

1 Answer 1

1

The thing is:

  • your component won't be displayed until busy is false because of *ngIf="!busy"
  • the $events won't be subscribed until the component is displayed (reminder: nothing happens in an Observable chain until there's a subscription)

Thus this cannot work: the subscription will not happen because the flag is true, and the flag will stay true because there's no subscription.

To workaround this, I'd subscribe in the Typescript code and get rid of the async pipe.

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

Comments

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.