Adding and Removing Items

Before we begin

Best practice in Angular is to move shared state into services that can be consumed across multiple components in your application. Because we declared our tracks in the dashboard.component.ts it is inaccessible to any other component directly, including the dashboard content. To be able to add or remove a card from anywhere other than the dashboard component itself, we will need to move the tracks variable into a service.

Before we continue it is important that you understand the concept of observable services. Observable services are regular services that return data, usually state, in the form of observables. If you are new to the concept of observable services and the advantages/disadvantages they come with, I recommend you read this article that covers the topic more in depth. For now, this will allow us to share the dashboard state which will be useful soon.

First, generate the dashboard service. Then copy the tracks array from the dashboard.component.ts into your service. I also renamed the variable to defaultState.

dashboard.service.ts

Second, create a subject that we can give data. A subject is like an EventEmitter with the ability to have multiple observers. In our case, we want to use a BehaviorSubject. A BehaviorSubject will emit the last given value to new listeners. We can create an observable from our subject by calling this.subject.asObservable(), I named that variable tracks$.

dashboard.service.ts

Finally, retrieve the tracks from the service in the dashboard component.

dashboard.component.ts

Now we can begin to add and remove tracks from the dashboard.

Removing Items

To remove items create a method on the dashboard service, I named it removeItem. Removed item will take an item as a parameter and attempt to remove the item from the tracks state and push the changes to the subject.

To get the state from a subject call subject.getValue(). This will give us a snapshot of the subject at that point in time. Now that we have the snapshot we can begin to manipulate it.

dashboard.service.ts

Remove the item by looping over each track in the state array. Then for each track loop over the items in the track. If the item in the loop matches the item provided as a parameter we then want to splice it out of the track. Once that is complete we want to pass the new state to the subject again by calling this.subject.next().

dashboard.service.ts

Adding Items

Create a method called addItem which will take an item and add it to one of the tracks. I chose to push the new item to the track with the least amount of items. Optional: you may want to validate that the item does not exist on either of the tracks before adding the item to prevent duplicates.

dashboard.service.ts

Before we can use the addItem/removeItem methods, we must go over how to make individual services calls from dashboard contents which is covered in the next section.