微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[Angular] State provider solutions

There are many ways to expose data to components, but based on different usecase, different solution has PROS & CONS.

 

1. ShareReplay(1)

PROS: ShareReplay(1) solves a problem which if you have multi subscribers, it will trigger API requests multi times if you don't have shareReplay(1) in place.

 

CONS: data is static, not dynamic. If you want to add/remove/update the data, you have to fetch new data again.

 

2. Subject as a service

We can keep a local copy of data using BehaviorSubject. Everytime, we add/remove/update, will trigger subject update.

 

PROS: Solve the problem for static data, Now it is dynamic and it won't trigger multi API calls.

CONS: It has race condition. If you try to add multi-times. it might happne that first request's response comes after second request's response. 

 

3. NgRx (ComponentStroe)

https://ngrx.io/guide/component-store

ComponentStore vs Global store: https://ngrx.io/guide/component-store/comparison

We need state for some components, it is not necessary add to global store.

 

PROS: It handles race condition by using effect (you can define your approach by using concatMap, switchMap, mergeMap, exhaustMap)

concatMap: is a good way to solve race condition.

switchMap: only care new request, ignore old one

exhaustMap: only care the current happening one,  ignore new ones during the period

Performance it better, NgRx using select() with memorized function.

 

CONS: Deep kNowledge of RxJS and NgRx.

 

Misc:

tapResponse:

From

to

 

 

 Refer: 

Filling the Gap in State with NgRx ComponentStore | Alex Okrushko | EnterpriseNG 2020

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐