Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to: Re-send an http request when using async pipe

Tags:

angular

rxjs

Is there a way to resend an HttpRequest when using the async pipe in the template like this?

myObservable$ = this.http.get('api');
<div *ngFor='let item of myObservable$ | async'>{{item}}</div>
like image 598
Bogdan B Avatar asked May 17 '19 13:05

Bogdan B


People also ask

How do async pipe handle errors?

The key point to making the async pipe work well with errors is to make sure you are using a consistent declarative/reactive approach - utilising the streams to handle errors - rather than mixing a reactive approach with imperative style programming (e.g. using the async pipe, but manually subscribing to streams and ...

Does async pipe automatically unsubscribe?

Every time a new value is emitted the async pipe will automatically mark your component to be checked for changes. And best of all, when the component is destroyed the async pipe will automatically unsubscribe for you. No need to do this manually.

What is Asyncpipe?

Angular's async pipe is a tool to resolve the value of a subscribable in the template. A subscribable can be an Observable , an EventEmitter , or a Promise . The pipe listens for promises to resolve and observables and event emitters to emit values. Let's take a look at how we can profit from using the async pipe.

How do you use async pipe?

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.


2 Answers

You need emit a new value to Observable, if you need refetch data by specific event, you can put the event to Observable and use switchMap for trigger fetching:

event$ = new BehaviorSubject(true);

myObservable$ = this.event$.pipe(
  switchMapTo(this.http.get('api'))
);

refetchData() {
  this.event$.next();
}

like image 82
izmaylovdev Avatar answered Oct 19 '22 05:10

izmaylovdev


Using async pipe is a very convenient way to deal with Observables, because it manages unsubscribing for you. Meaning, that if myObservable$ reference changes, ChangeDetection will be triggered and async will unsubscribe current subscription and subscribe to another. So you can simply reassign new value myObservable$ and HttpRequest will be sent again.

test it out yourself:

ngOnInit() {
  setTimeout(() => this.myObservable$ = this.http.get('another-endpoint'), 2000)
}
like image 2
Julius Dzidzevičius Avatar answered Oct 19 '22 07:10

Julius Dzidzevičius