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>
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 ...
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.
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.
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.
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();
}
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With