我想从observable中提取项,并通过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[]'.为什么它返回空?
发布于 2018-07-24 21:03:11
array.forEach不返回值,因为它只是用于迭代。因此year.forEach不会向map返回任何内容,因此void也不会返回任何内容。
您需要使用year.map并返回一个值
发布于 2018-07-24 21:06:08
您正在从类型为"PolicyYears[]“的policeYears$映射数据
因此,您必须将代码更改为
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.PolicyYear[]
温馨的问候
发布于 2018-07-24 21:32:25
问题是Array.forEach返回void (因此您会收到错误消息,因为您现在正尝试使用map将PolicyYear[]映射到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;
}))https://stackoverflow.com/questions/51499252
复制相似问题