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>
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)
}
async does the work for us, we don't need to give any more instructions. So for this code snippet it appears to be even more declarativeThis is not the best practice. The async pipe is meant to be used with streams, using it with trigger observables such as http calls can have unwanted side effects. I suggest putting the http call in a service, and subscribing in your component. If there's a specific reason you want to use the async pipe, I suggest having a separate BehaviorSubject and doing something like this....
_myBehaviorSubject = new BehaviorSubject(null);
myBehaviorSubject$ = this._myBehaviorSubject.asObservable();
myObservable$ = this.http.get('api').pipe(tap(items => this._myBehaviorSubject.push(items)));
Then, in your component, you can subscribe to this every time you want to make an http call, and in your html template, subscribe to myBehaviorSubject$ using the async pipe.