当用户单击按钮时刷新 Observable 数据

mac*_*pak 1 rxjs angular

我有一个 Angular 6 组件,其中我有一个网格,它使用异步管道订阅带有项目的 observable。我想要一个按钮,单击该按钮时会刷新该 observable 中的数据。我添加了以下代码:

public refreshData(): void {
   this.details$ = this._service.getDetails();
}
Run Code Online (Sandbox Code Playgroud)

然后,在模板上:

*ngIf="(details$ | async); let d"
Run Code Online (Sandbox Code Playgroud)

所以现在,每次用户单击按钮时,都会执行 refreshData 方法。该代码有效,数据已刷新,但我正在为每次点击创建一个新的可观察对象。有没有更好的方法来处理?

Jot*_*edo 6

正如所评论的那样,一种更具反应性的方法如下:

import {Subject,Observable} from 'rxjs';
import {startWith,switchMap} from 'rxjs/operators';

class FooComponent implements OnDestroy {
  private readonly refreshClick$ = new Subject<void>();
  readonly details$ : Observable<FooDetails>;

  constructor(...){
    this.details$ = this.refreshClick$.pipe(
     // fake emission of a click so that initial data can be loaded
     startWith(undefined),
     switchMap(() => this._service.getDetails())
    );
  }

  ngOnDestroy(){
    // "complete" should be invoked on subjects once their lifetime is complete
    refreshClick$.complete();
  }

  refresh(){
    this.refreshClick$.next();
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用在初始化时发出的“private readonlyfreshClick$ = newBehaviourSubject&lt;void&gt;(null);”。那么你就不需要使用 `startWith(undefined)` 来进行假发射 (4认同)