【问题标题】:Rxjs actions on observable start (opponent of finalize)可观察开始时的 Rxjs 操作(finalize 的反对者)
【发布时间】:2019-12-24 21:55:18
【问题描述】:

在我当前的 Angular 项目中,我需要在订阅 observable 时执行特定操作。 因此,我正在寻找 finalize 运算符的对手。 当 observable 完成或出错时,Finalize 运算符调用函数。就我而言,我需要在可观察开始时调用一个函数。 => 你知道我怎么能这样吗?

更新以澄清我的要求: 在服务中,我有一个返回 Observable 的 init 方法。 多亏了 pipable 操作符,所有的逻辑都在 observable 内部,因为 initObservable 可以在多个组件中订阅(避免代码重复)同时(这就是我使用共享运算符的原因)例如:

private initObs$: Observable<Data> = htttp.get('URL form where I get Data').pipe(
    tap(// do stuff with Data (init the store with Data in my case)),
    catchError(//Error handeling),
    finalize(// do onComplete actions ex: hide spiner overlay),
    share() // As this observable may be subscribed simultaneously by different subscriber
);

由于这个 Obsevable 可能同时被不同的组件订阅,我想在 Observable 本身内添加显示微调器叠加层的操作,以避免在每个组件中出现如下代码:

this.spinnerservice.show();
this.DataService.initObs$.subscribe();

提前致谢

【问题讨论】:

标签: angular rxjs


【解决方案1】:

你正在寻找延迟:

initObs$ = defer(() => {
  // do whatever, show spinner etc
  return htttp.get('URL form where I get Data').pipe(
    tap(// do stuff with Data (init the store with Data in my case)),
    catchError(//Error handeling),
    finalize(// do onComplete actions ex: hide spiner overlay)
  );
}).pipe(share());

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-21
  • 2020-12-22
  • 2022-12-14
  • 2021-08-22
相关资源
最近更新 更多