【发布时间】:2020-09-14 21:51:30
【问题描述】:
在我的 html 中,我使用异步管道来订阅 observable,如下所示。
<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>
每当用户点击按钮 1 或 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。并且由于这个新的 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
【问题讨论】:
-
为什么不直接创建一个静态变量
let user,然后将请求转换为在完成时更新用户的承诺?this.getDataFromBackend(id).toPromise().then( data => (this.user = data))。不需要异步管道,只需显示用户。
标签: angular rxjs observable angular2-observables rxjs-pipeable-operators