【发布时间】:2022-01-16 07:51:30
【问题描述】:
当我使用combineLatest 组合两个发出可选值的可观察对象时,我经常在 Angular 中遇到这种情况。
基本模式是这样的:
const ob1: Observable<Transaction[] | null>;
const ob2: Observable<Price[] | null>;
const currentValue = combineLatest([ob1, ob2]).pipe(
filter(([a, b]) => !!a && !!b),
map(([a, b]) => {
// Here the type of both and a and b is nullable
const x = a.map(a => a.id); // This gives compilation error that a can be null
});
我想在map 函数中工作,以便在两个可观察对象发出非空值时合并事件。
filter 确实会过滤,但每个元素的类型仍然是 T | null。
我希望a 的类型为Transaction[],b 的类型为Price[],而不使用a! 或b!。
这种模式在我的代码中重复了很多次,我想找到一个简短而优雅的解决方案,并且不需要我为每个用例编写样板代码。
我找到了一些答案how to fix this for a single value。但是如何为元组或数组执行此操作?
【问题讨论】:
标签: angular typescript rxjs