重用RxJS Observable重复异步调用吗? [英] Re-using an RxJS Observable to repeat an asynchronous call?

查看:44
本文介绍了重用RxJS Observable重复异步调用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果基础事件流不发出新值,那么RxJS Observable如何发出新值?

How can an RxJS Observable emit a new value, if the underlying event stream doesn't emit a new value?

给出一个使用异步 pipe 来显示用户名的Angular组件;

Given an Angular component which uses an async pipe to display a user's name;

export class MyComponent implements OnInit {

  public user$!: Observable<User>;

  constructor(private readonly ms: MyService)

  ngOnInit() {
    this.user$ = this.ms.getUser();
  }
}

<ng-container *ngIf="user$ | async as user; else empty">
  {{ user.name }}
</ng-container>

<ng-template #empty>
  No user here.
</ng-template>

...想象一些时间过去了,我想尝试通过调用异步函数 this.ms.getUser()重新获得用户,我该怎么做?

...imagine some time passes and I want to try getting the user again by calling the asynchronous function this.ms.getUser(), how can I do this?

AFAIK,我不能简单地覆盖Observable $ captcha ;

AFAIK, I cannot simply overwrite the Observable $captcha;

export class MyComponent implements OnInit {

  public user$!: Observable<User>;

  constructor(private readonly ms: MyService)

  ngOnInit() {
    this.user$ = this.ms.getUser();
  }

  getUserAgain() {
    // Wrong. This would be a new/different Observable.
    // The UI would not update.
    this.user$ = this.ms.getUser();
  }
}

服务 MyService 返回一个Observable,因为它只是Angular的 HttpClient 的薄包装.

The service MyService returns an Observable because it's just a thin wrapper around Angular's HttpClient.

推荐答案

我建议尽可能多地使用可观察对象,并保持反应灵敏"状态:

I'd recommend to use observables as much as possible and stay in a "reactive mind":

export class MyComponent {
  public refreshUser$: Subject<void> = new Subject();

  public user$!: Observable<User> = this.refreshUser$.pipe(
    startWith(undefined),
    switchMap(() => this.ms.getUser())
  );

  constructor(private readonly ms: MyService) {}

  public getUserAgain() {
    this.refreshUser$.next();
  }
}

这篇关于重用RxJS Observable重复异步调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆