Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

rxjs - Angular single observable, multiple observers

learning angular got to services and component and observables.

I'm trying to implement a dark mode in my demo app. The control is done by a service which sets the dark theme based on the browser default if found.

Its initialized in the app component to later have control switches to be placed in the app.

The dark mode works from a boolean value so either true or false. As I understand using an observable isnt enough as I want multiple subscribers to all bind two ways to the subscription each in a different way toggling these observable in the service. I'm pretty sure that's correct so far.

The part I'm stuck. Say if you want 3 different components a button component I the toolbar, a checkbox in the settings and toggle switch in users main settings for example.

How would you use make the 2 way link between the observable in the services and each component so that when each component emits the toggle event all update ? I'm pretty sure behaviourSubject or subject observables are the correct route to go but the angular docs really only go into single case use ? Unless I cant see it and further explanation in the difference of these observables seems to be limited as to the difference between them. One returning from the init value other now but not their implementation across multiple components

Do you have a global observable that the components all create individual observables on init to update the view.. I'm clueless.. it seems so simple yet when trying to out it in practice mind boggling.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sounds like you want to share an observable between multiple components, and have each component listen to it and modify it by toggling on/off?

You could use a singleton service and subscribe to the subject in your components? This stackblitz is fairly crude, but its an example of separate components updating a single shared source observable. In this case it doesn't have to use a BehaviorSubject either, can just do a regular subject. Behavior subject could be useful to default to light mode if you wanted to.

https://stackblitz.com/edit/angular-ox4utu


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...