RxAngular Integration
There are use cases when is desired to have a transient component state has it's lifetime bound to the component lifecycle. RxAngular provides a solution for this problem that is fully reactive and with focus on runtime performance and template rendering.
In order to leverage this library and all the power of a global state management is possible to integrate RxAngular with NGXS. First, let's bind a value from NGXS state to RxAngular component state:
1
interface HeroesComponentState {
2
heroes: Hero[];
3
}
4
5
const initHeroesComponentState: Partial<HeroesComponentState> = {
6
heroes: []
7
};
8
9
@Component({
10
selector: 'app-heroes',
11
templateUrl: './heroes.component.html',
12
styleUrls: ['./heroes.component.css'],
13
providers: [RxState] // <--- This binds RxState to the lifetime of the component
14
})
15
export class HeroesComponent {
16
@Select(getHeroes) stateHeroes$: Observable<Hero[]>; // <--- normal @Select use from NGXS
17
18
heroes: Hero[];
19
20
readonly heroes$: Observable<Hero[]> = this.state.select('heroes');
21
22
constructor(
23
private state: RxState<HeroesComponentState>,
24
) {
25
this.state.set(initHeroesComponentState);
26
this.state.connect('heroes', this.stateHeroes$); // <--- Here we connect NGXS with RxAngular
27
}
28
}
Copied!
It is also important to connect the changes on the component local state to NGXS. For example, let's bind the addHero and deleteHero on the following code:
1
@Component({
2
selector: 'app-heroes',
3
templateUrl: './heroes.component.html',
4
styleUrls: ['./heroes.component.css'],
5
providers: [RxState]
6
})
7
export class HeroesComponent {
8
heroes: Hero[];
9
10
readonly add = new Subject<string>();
11
readonly delete = new Subject<Hero>();
12
13
constructor(
14
private state: RxState<HeroesComponentState>,
15
private store: Store
16
) {
17
18
this.state.hold( // <--- RxAngular hold will manage the subscription for us
19
this.add.pipe(switchMap(name => this.store.dispatch(new AddHero(name)))) // <--- dispatch action to NGXS
20
);
21
22
this.state.hold(
23
this.delete.pipe(
24
switchMap(hero => this.store.dispatch(new DeleteHero(hero)))
25
)
26
);
27
}
28
}
Copied!
That's it! The advantage of this approach is that you can leverage all the reactivity from RxAngular and still manage your global state using NGXS. This allows you to combine the best of both libraries.
To check a full example integrating NGXS with RxAngular checkout this Tour of Heroes example here
Last modified 1yr ago
Copy link