One of the cool things about teaching Angular, running an Angular certification program, and interacting with hundreds of developers (and code bases) all around the world is that I get to see a lot of good ideas but also a lot of repeated mistakes.
Today, I want to share a small code challenge inspired by repeatedly seen examples over the past few weeks, so you can learn from these examples and won’t make these mistakes in the future.
Here is an example of service for you to look at:
The challenge I have for you is to answer these questions:
- What do you think is the requirement behind the code in that service? Why use the
shareReplay
operator? - Assuming that three different components call the
getData()
method in their constructor to get an Observable and subscribe to it using the async pipe, how many requests will be made to the API server? - Is the original requirement met or not? How to fix that code if it isn’t working correctly?
I’ll give you these answers tomorrow. In the meantime, feel free to reply with your own answers if you want.