如何显示上一个可观察的数据,直到新的可观察到的发射值为止

问题描述 投票:0回答:2

在我的html中,我正在使用异步管道来订阅如下所示的可观察对象。

<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>

并且每次用户单击button1或2时,这个可观察到的userData $都会变为新的。

  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));
  }

现在每当用户从user1更改为user2时,就会分配新的可观察对象。并且由于这个新的Observable当时需要一些时间来获取数据,因此它显示为空。

我们可以做些什么,以便在不返回新的可观察数据之前,我们可以显示以前的数据。

  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

下面是stackblitz显示问题的链接。

https://stackblitz.com/edit/angular-ivy-d9nsxu?file=src%2Fapp%2Fapp.component.ts

angular rxjs observable angular2-observables rxjs-pipeable-operators
2个回答
0
投票

您可以在*ngIf块中添加else块。尝试以下操作

<div *ngIf="userData$ |async as user; else elseBlock">
  data is {{ user | json }}
</div>
<ng-template #elseBlock>
  Loading...
</ng-template>

我已经修改了您的Stackblitz


0
投票

数据消失的原因是因为您用新的可观察对象立即覆盖了userData$对象,但尚未返回结果。

也许您可以订阅getDataFromBackend调用并在返回结果后覆盖userData $:

  userData$ = new Subject();
  dataSource = {1:{user:'user1', id:1}, 2: {user:'user2', id:2}};

  getData(id) {
    this.getDataFromBackend(id).subscribe(res => this.userData$.next(res));
  }
© www.soinside.com 2019 - 2024. All rights reserved.