【问题标题】:Reactive Loading state management with RxJs使用 RxJs 进行响应式加载状态管理
【发布时间】:2023-01-23 01:49:23
【问题描述】:

当你有一些输入字段并且你必须在值更改时获取一些东西时的经典任务。假设我们使用 Angular Reactive Forms。例子:

orders$ = inputControl.valueChanges.pipe(
   switchMap((value) => {
     return someService.fetch(value);
   })
);

现在我们还应该以某种方式管理加载状态。我通常使用tap

orders$ = inputControl.valueChanges.pipe(
  tap(() => { loading = true }), // or loading$.next(true) if loading is a subject
  switchMap((value) => {
    return someService.fetch(value);
  }),
  tap(() => { loading = false }), // or loading$.next(false) if loading is a subject
);

然而,我们似乎可以通过某种方式避免在 tap 中赋值,而是使用 RxJs。 但是我找不到处理它的方法。

对我来说,理想解决方案的用法是

orders$ = <some abstraction here that depends on inputControl.valueChanges and fetching>
loading$ = <some abstraction here that depends on fetching>

【问题讨论】:

    标签: javascript angular rxjs reactive-programming


    【解决方案1】:

    您可以使用 map 和 shareReplay 运算符来实现此目的。 map 运算符可用于从服务调用返回值,而 shareReplay 运算符可用于共享可观察对象并保持加载状态。

    orders$ = inputControl.valueChanges.pipe(
      switchMap((value) => {
        return someService.fetch(value).pipe(
          map(data => {
            loading$.next(false);
            return data;
          }),
          startWith({loading: true})
        );
      }),
      shareReplay(1)
    );
    loading$ = orders$.pipe(map(data => data.loading));

    这样你就可以使用 orders$ observable 来订阅订单,使用 loading$ observable 来订阅加载状态。 注意:如果您从服务调用返回一个对象,上面的示例将不起作用,您需要将该对象包装在另一个具有加载属性的对象中,如 {data: {}, loading: true/false}

    【讨论】:

      猜你喜欢
      • 2020-12-02
      • 2020-01-26
      • 1970-01-01
      • 2020-11-29
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 2021-07-30
      • 2021-12-23
      相关资源
      最近更新 更多