rxjs 中基于 boolean observable 的条件 observable 转换
Conditional observable transformation based on boolean observable in rxjs
我如何根据布尔 Observable 编辑我的 Observable 值,只要这个布尔 Observable 发生变化,$ships
Observable 就会被转换。
areShipsExpanded$: Observable<boolean>;
ships$: Observable<Ship>;
this.ships$ = this.shipsDataSource.getData().pipe(
map(s => {
if(this.areShipsExpanded$) {
// do something with s
} else {
// do something else with s
}
return s;
})
当然会在视图中使用 ships$ | async
以上代码不正确,因为当 this.areShipsExpanded$
发生变化时 Observable 不会再次转换。
areShipsExpanded$: Observable<boolean>;
ships$: Observable<Ship>;
this.ships$ = this.shipsDataSource.getData().pipe(
combineLatest(this.areShipsExpanded$),
map(([ships, expanded]) => {
if(expanded) {
// do something with ships
} else {
// do something else with ships
}
return ships;
})
我如何根据布尔 Observable 编辑我的 Observable 值,只要这个布尔 Observable 发生变化,$ships
Observable 就会被转换。
areShipsExpanded$: Observable<boolean>;
ships$: Observable<Ship>;
this.ships$ = this.shipsDataSource.getData().pipe(
map(s => {
if(this.areShipsExpanded$) {
// do something with s
} else {
// do something else with s
}
return s;
})
当然会在视图中使用 ships$ | async
以上代码不正确,因为当 this.areShipsExpanded$
发生变化时 Observable 不会再次转换。
areShipsExpanded$: Observable<boolean>;
ships$: Observable<Ship>;
this.ships$ = this.shipsDataSource.getData().pipe(
combineLatest(this.areShipsExpanded$),
map(([ships, expanded]) => {
if(expanded) {
// do something with ships
} else {
// do something else with ships
}
return ships;
})