Angular applications rely on data for building the elements that are displayed on components. A common practice is to add an object array to a component and directly call HTTP services to load the array. The following basic example demonstrates this practice.
The basic component has its own data array and subscribes to the API service to load the array. Note: In a real scenario, the API service would be calling an actual API endpoint. Considering how simple the example is, there’s quite a bit there for the basic component to manage. The basic component knows about the model and the API service. As more elements are added, the basic component could easily balloon into a several http services, arrays and calls.
What I like to do is decouple the component, the data array and the API call. This way the component knows just enough to get what it needs…namely, a service and its models. To accomplish this, we introduce another service to create separation between the test component and the API service. The new service will be responsible for holding the models and calling the API service.
Now instead of the component managing everything, it offloads those responsibilities to the test service. The test service has a BehaviorSubject to hold its data array which it exposes through the model’s getter property.
The decoupled component sheds its data array and now only needs to import the test service. Notice the reference to the test service’s models is in the decoupled component’s html template. Using the BehaviorSubject, the decoupled component will now rely on the test service to manage the data. Other details about the http call and models are extracted from the component into the test service. Now the decoupled component can import many other services without getting bogged down with the details of each.
I like this approach to keep components simple and extendible. I hope you find this example useful. Thanks.
Please find the StackBlitz at: