we are going to create a service that will communicate between our grid component and our difficulty component, so to do that let's first create a difficultyBusService; again just my naming convention.
ng generate service services/difficultyBus/difficultyBus
in our services folder we should now see the following
by default when we added our service we see that it is a singleton, meaning that it is shared between all of our various componenets where it is injected
the above class attribute ensures that only one difficulty bus exists that is shared amongst any components that instantiate it
we have added three bits of code here
- The backing field is an instance of the Subject object from RxJS. Is an implementation of the observer pattern
- The readonly observable property allows our "watching" object to subscribe to changes
- The setDifficulty method allows a class to push a difficulty to our BUS service which will then emit the change
Now that we have configured our bus, in this case it will be a one way bus, communicating from our difficulty component to our grid component, lets configure our difficulty component to publish a change in difficulty.
Now we only made two very simple changes here:
- In the constructor we inject our DifficultyBusService which facilitates this cross component communication.
- In the SelectDifficulty method which is fired every time we change the difficulty we set the new difficulty, now as you may recall what will happen is in the difficultyBusService we are going to call the next method on our difficulty subject which in turn will notify any watchers who have subscribed to the difficultyObservable.
now here is where we make the bulk of our changes:
- We inject our DifficultyBuss into the constructor, now as we mentioned before it is a singleton, meaning that no matter how many times we inject it it is always the same instance, so the difficulty bus in this class is in memory the same difficulty bus as in our difficulty component.
- In the ngOnInit function we subscribe to the difficultyObservable property which will execute the delegate function which we defined, in this case it will alert us to the difficulty and set the backing field accordingly.
- for good measure we reference this Subscription (from rxJS) which then allows us to unsubscribe from this observable should the component ever be destroyed, we do this to prevent memory leaks. In this app it is unnecessary since neither of these components will ever be destroyed , however it is always good practice.
- in our on mark method we call a different endpoint based on what the difficulty is.
- and finally we created this private markOnBoard method that we can pass to the service we use to figure out our next move to mark that move on the grid DRY principle