0

让我解释。我有一个订阅,它返回一个带有属性的对象。history 属性通常获取一个字符串,但它也可以为空。我怎么能处理分开 2 个分支。我的意思是,如果 history 属性的值是一个字符串,则返回它,如果它是 null 则显示“无历史记录”。我知道 operator iif,但在这种情况下,怀疑不是关于检索一个或另一个 observable 的条件,我的意思是在同一个 observable 流中。

this.historyResult$ = this.historyObject$.pipe(
                            pluck('history')
                            );

总结一下:我的问题是,我是否可以设置类似条件的内容:如果历史记录的值为空,则例如使用运算符 mapTo ('No history') 以检索 'No history' 字符串?

4

2 回答 2

2

您可以简单地使用map运算符。如果x.historyundefined,则空值合并运算符 通过 .内部的匿名函数??返回字符串。以便发出属性或字符串:"No history"maphistory

this.historyResult$ = this.historyObject$.pipe(
  map((x) =>
    x.history ?? "No history"
  ),
);
于 2021-03-25T14:16:31.973 回答
0

看看filter-operator ( https://www.learnrxjs.io/learn-rxjs/operators/filtering/filter )

使用此运算符,您可以通过以下方式按缺失值进行过滤:

this.historyResult$ = this.historyObject$.pipe(
    pluck('history'),
    filter((history) => !!history)
);

这样你的 observable 将永远不会产生 a nullorundefined值。

于 2021-03-25T13:56:14.190 回答