如何通过RXJS中的另一个可观察对象来修改可观察对象流?角度的

时间:2018-07-27 13:12:55

标签: angular rxjs rxjs6

当标志ships$将更改时,我想更改areShipsExpanded$中的嵌套标志。 我怎样才能做到这一点。这是我到目前为止的内容:

areShipsExpanded$: Observable<boolean>;
ships$: Observable<Ship>;

constructor() {
   this.ships$ = this.shipsDataSource.getData().pipe(shareReplay());
}

ngOnInit(): void {
    this.areShipsExpanded$.pipe(
        map(flag => {
            if (flag) {
                this.ships$.pipe(map(s => s.items.forEach(r => r.isExpanded = flag)));
            }
        })
    ).subscribe();
}

不幸的是,ships $似乎没有被修改,或者也许我应该以某种方式刷新此ships$可观察到的位置,因为我以这种方式在视图上使用它:<ng-container *ngFor="let ship of (ships$ | async)?.items">


@EDIT

我是以这种方式做到的,是正确的还是不好的做法?

this.areShipsExpanded$.pipe(
    map(flag => {
        if (flag) {
            this.ships$ = this.ships$.pipe(map(s => {
                s.items.forEach(r => r.isExpanded = flag);
                return s;
            }));
        }
    })
).subscribe();

@ EDIT2

我用过combineLatest,现在应该还好吗?

shipsData$: Observable<Ship>;
ships$: Observable<Ship>;

constructor() {
   this.shipsData$ = this.shipsDataSource.getData().pipe(shareReplay());
}

this.ships$ = combineLatest(this.areShipsExpanded$, this.shipsData$).pipe
    map(([shipsExpanded, ships]) => {
        ships.items.forEach(r => r.isExpanded = shipsExpanded);
        return ships;
    }),
    share()
);

但是combineLatest的问题是,在开始时函数将运行2次,因为两个可观察对象都发出值。是否有任何类似combineLatest的运算符-因此,当任何可观察对象发出值时,请从每个观察对象发出最新值,但仅当所有可观察对象准备就绪时。为了避免在开始时重复。

1 个答案:

答案 0 :(得分:0)

这可能对您有帮助吗

const fetchData$ = this.shipsDataSource.getData().pipe(shareReplay());

this.ships$ = merge(
    this.areShipsExpanded$.pipe(
        withLatestFrom(fetchData$),
        map(([shipsExpanded, ships]) => 
            // we could try to favor immutability
            ships.items.map(r => {...r, isExpanded:shipsExpanded})), 
    ), // ships after update
    fetchData$ // initial ships
).pipe(share());