我得到一个对象数组(Observable<MyClass[]>
)的Observable,因此当我tap
观察对象时,我看到的是数组而不是元素本身。我想更改数组中的对象而不是数组本身,我很难做到这一点。
实际的类是
{date: Date, activity: boolean, activityId?:string, first?: boolean, last?: boolean, ...}
const array$: Observable<MyClass[]> = of([{date: new Date(), activity: true},{date: new Date(),
activity: false},{date: new Date(), activity: false}]).pipe(tap(console.log));
当一天的活动为假,并且不是前一个活动时,则应将第一个布尔值设置为true等,但是当我很难不引入副作用时。
在pipe()
内,我尝试先做concatMap
,然后再做toArray()
,但是当我在toArray
之前点击时,我看到了每个元素,可以更改它们,但是toArray
之后的实际输出与我输入到html中的原始值不一样,因此它什么也不显示。与下面的答案相同。
对我所得到的简化版本进行了堆栈闪电扫描。
https://stackblitz.com/edit/angular-jvbvhx?embed=1&file=src/app/app.component.ts
答案 0 :(得分:0)
您可以在RxJS Array.map
中使用map
:
const modified$ = original$.pipe(
map(array => array.map(element => modifyElement()))
);
您也可以仅使用RxJS运算符来完成此操作,但是随后需要选择所需的特定行为。一种选择:
const modified$ = original$.pipe(
concatMap(array => from(array)),
map(element => modifyElement()),
toArray()
);
答案 1 :(得分:0)
map
方法还使用index
和array
作为参数,然后可以像这样将其归档:
schedule$ = of(this.createSchedule()).pipe(map( arr => arr.map((date, i, arr) => {
//when activity is false and the previous wasn't set the first boolean true
if( date.activity == false && i > 0 && arr[i - 1].activity == false ) {
arr[i - 1].activity = true;
}
//when activity is false and the next isn't set the last boolean true
if( date.activity == false && arr[i + 1].activity == false ) {
arr[i + 1].activity = true;
}
return date
})), tap(console.log))