In my html i am using async pipe to subscribe the observable like shown below.
<button (click)="getData(1)" >getUser1</button>
<button style="margin:50px;" (click)="getData(2)" >getUser2</button>
<div>------------------------------------------</div>
<div *ngIf="userData$ |async as user">
data is{{ user | json}}</div>
and this userData$ observable become new each time user click on button1 or 2.
getData(id) {
this.userData$ = this.getDataFromBackend(id);
}
getDataFromBackend(id) {
//delay added to simulate network delay
// fake backend call but i have to use real one in actual project
return of(this.dataSource[id]).pipe(delay(1000));
}
now whenever user change from user1 to user2 the new observable is assigned. and since this new observable takes some time to get data for that time being it shows empty.
can we do something so that till the time the new observable data is not return we can show the previous data.
I can not user loader here meanwhile.
I know i can do something like
let subject = new Subject();
let userObservable$ = subject.asObservable()
and use this observable in the html
and the subscribe to these observable form getDataFromBackend() here in the class and from
subscription do the subject.next() and it will send the updated value
but this does not seem the best way as it do the manual subscription in the component
below is the linke for stackblitz showing the problem.
https://stackblitz.com/edit/angular-ivy-d9nsxu?file=src%2Fapp%2Fapp.component.ts
let user
then turn the request into a promise that updates user on completion?this.getDataFromBackend(id).toPromise().then( data => (this.user = data))
. No async pipe needed, just display user. – Z. Bagley