Observable中的Foreach用于转换



我想从observable中获取Item,并通过foreach对其进行转换,然后将结果保存到新变量中。

我不确定为什么这个代码不起作用:

policYears$: Observable<PolicyYear[]>;
policYearsSelector$: Observable<YearSelector.PolicyYear[]>;
this.policYearsSelector$ = this.policYears$.pipe(
map((year: YearSelector.PolicyYear[]) => year.forEach(y => y.isActive = this.params.policyYearIds.indexOf(y.id) !== -1))
);

我有一个错误:Type 'Observable<void>' is not assignable to type 'Observable<PolicyYear[]>'. Type 'void' is not assignable to type 'PolicyYear[]'.为什么它会返回虚空?

array.forEach不会返回值,因为它只是用于迭代。因此year.forEach不向map返回任何内容,而CCD_5则不返回任何内容。

您需要使用year.map并返回一个值

您正在从policeYears$映射数据,其类型为"PolicyYears[]">

所以你必须把你的代码改成

policYears$: Observable<PolicyYear[]>;
policYearsSelector$: Observable<YearSelector.PolicyYear[]>;
this.policYearsSelector$ = this.policYears$.pipe(
map(
(year: PolicyYear[]): YearSelector.PolicyYear[] => 
year.forEach(
y => y.isActive = this.params.policyYearIds.indexOf(y.id) !== -1
)
)
);

year的类型为PolicyYear[],映射返回一个YearSelector。保单年度[]

热烈问候

问题是Array.forEach返回void(因此是您收到的错误消息,因为现在您正试图使用mapPolicyYear[]映射到void(。

现在,根据你想做什么,你可以继续使用forEach,只返回更新后的数组:

map((year: YearSelector.PolicyYear[]) => {
year.forEach(y => y.isActive = this.params.policyYearIds.indexOf(y.id) !== -1);
return year;
})

或者您可以使用Array.map并返回一个新数组:

map((year: YearSelector.PolicyYear[]) => year.map(y => {
y.isActive = this.params.policyYearIds.indexOf(y.id) !== -1;
return y;
}))

最新更新