【问题标题】:How to call "defaultIfEmpty" when list is empty on RxJS?当 RxJS 上的列表为空时,如何调用“defaultIfEmpty”?
【发布时间】:2022-09-23 01:25:25
【问题描述】:

我有两个需要转换为相同类型的具有两个不同对象的列表,只有当“first”列表为空时才会使用“second”列表,我尝试使用方法@987654321 @ 但它永远不会返回第二个选项。

const first = []; // could be [{code: 1}, {code: 2}]
const second = [{id: 1}, {id: 2}]

of(first).pipe(
    map((value) => {number: value.code})
).pipe(
    defaultIfEmpty(of(second).pipe(map((value) => {number: value.id})))
).subscribe(doSomething);

所需的输出是:

[{number: 1}, {number: 2}]

在上面的例子中,来自defaultIfEmptymap 永远不会被调用;

  1. 如果给定源为空,我如何“切换”到另一个方法源?
  2. 是在map 完成后调用subscribe 方法,还是为map 上的每个项目调用它?

    标签: rxjs


    【解决方案1】:
    const list1: { code: number }[] = [];
    const list2 = [{ id: 1 }, { id: 2 }];
    
    of(list1)
      .pipe(
         map((aList) => aList.map((v) => ({ 'number': v.code }))),
         map((listModified) => {
           return listModified?.length > 0
              ? listModified
              : list2.map((value) => ({ number: value.id }));
         })
       )
       .subscribe(console.log);
    

    不要和map混淆,其中一个来自rxjs,另一个是数组的函数。在您的第一个 map 中,您映射的是整个数组,而不是每个元素。

    subscribe 将在 pipe 内完成所有操作时调用。

    【讨论】:

      【解决方案2】:

      如果这是一个选项,只需在运行时创建正确的 observable:

      const makeObservable =
        (arr1, arr2) =>
          from(arr1.length ? arr1 : arr2)
            .pipe(map(({code, id}) => ({number: code ?? id})));
        
      const obs1$ = makeObservable([], [{id:1},{id:2}]);
      const obs2$ = makeObservable([{code:2},{code:3}], []);
      
      obs1$.subscribe(o => console.log(o));
      obs2$.subscribe(o => console.log(o));
      <script src="https://unpkg.com/rxjs@%5E7/dist/bundles/rxjs.umd.min.js"></script>
      <script>
      const {from} = rxjs;
      const {map} = rxjs.operators;
      </script>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-10
        • 2013-08-31
        • 2021-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多