Code challenge #3 solution

Before I dive into the solution of code challenge #3, I wanted to mention that my next FREE workshop is scheduled for April 4th. It will be all about getting into RxJs from scratch, and you can register here. I’ll start from the basics and move on to more advanced topics, such as subjects and operators, and you’ll be able to ask me questions as we go through the content and exercises together.

As always, it’s a free workshop, but your coffee donations are always welcome.

Let’s get into our code challenge solution. The goal was to “connect” two different dropdowns so that the selection of the first dropdown (a continent) would update the contents of the second dropdown (a list of countries for that continent):

The challenge is that countries depend on two different Observable data sources:

  1. An HTTP request to an API to get the list of all countries in the world
  2. The currently selected continent (a reactive form select dropdown)

In other words, we start with the following code:

Our goal is to combine data from both Observables into one result. Ideally, such a result would be updated whenever any of the Observable sources are updated (e.g., a new continent is selected by the user, or a new list of countries is available from the API).

As a result, we can use the withLatestFrom operator to make that “connection” between our two Observables:

Such an operator returns an array of all the latest values of our source Observables in the order in which they were declared. As a result, we can use the map operator to receive that array and turn it into something different:

Inside that operator, we decide to return a new array. The continent remains the same, and we filter the list of countries based on that continent:

FInally, we can use tap to run some side effects. In our case, we update the list of countries used by the dropdown, and we set the country dropdown value to the first country of that list to ensure that a country from a previous continent doesn’t remain selected:

And that’s it! You can see that code in action on Stackblitz here.

A few of you sent me their own solutions to the challenge, and a recurring theme was that most of you didn’t “connect” the Observables and just assumed that the list of countries would already be downloaded and available by the time the user selected a continent. Something along those lines, where this.countries would be received from the API before that code runs:

While the above code would work most of the time, if a user selects a continent before this.countries is defined, an error would be thrown and the corresponding subscription destroyed, which means the above code would not run anymore when the user selects a new value. As a result, using operators is safer.

Another trick in my solution is that I didn’t use any .subscribe in my code, which means I don’t have to unsubscribe, as I let the async pipe do so for me automatically:

That’s it for code challenge #3! Next week, I’ll send you updates from ng-conf in Salt Lake City. If you’re around, feel ree to come say hi!

Code challenge #3: RxJs Wizardry

It’s been a few months since our last code challenge, where the goal is to have you look at some code that isn’t working and make you improve your Angular skills along the way.

In this code challenge #3, we have two select dropdowns that have to work together so that when we select a continent, we can only see countries from that continent in the second dropdown. The current code isn’t working – Argentina isn’t in Europe, so this selection should not be possible:

You can fork that code from Stackblitz here. Feel free to email me your solution once you have one ready. I’ll send you a possible solution in next week’s newsletter.

In case you missed my previous code challenges, here they are, along with the link to their respective solutions:

Code challenge #2 Solution

In yesterday’s code challenge, our application wasn’t displaying any data. There were two reasons for that problem:

  1. HttpClient was not provided in the application
  2. The change detection strategy OnPush wasn’t compatible with the data flow of the application

I’m including links to previous newsletter entries for deeper dives on the different topics involved in that solution. And there are quite a few subtleties to overcome.

Let’s tackle the first issue, which was providing the HTTP client. We can use one of the several utility functions for standalone app config, in our case, provideHttpClient:

The second problem can be solved in two different ways:

  1. Remove change detection onPush to use the default one instead
  2. Use the async pipe or Signals to trigger change detection in that OnPush component

Because it’s always better to use the async pipe, I’m going with that option in our template:

In our component class, I stored the Observable from our service instead of storing the data. No more constructor needed:

You can see that solution in action on Stackblitz here. We fixed our code and added some performance improvements as well by ensuring we can’t get into memory leaks and optimizing change detection for that component.

Code challenge #2: DI or not DI?

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 mistakes seen over the past few weeks so you can learn from these examples and hopefully won’t make these same mistakes in the future.

Here is the code I want you to look at:

You can run it on Stackblitz here and fork the project to debug what’s wrong and make it work. Currently, this App component displays nothing at all, which is a problem.

I’ll give you a possible solution tomorrow. In the meantime, feel free to send me your solution if you want.

ShareReplay Code Challenge #1 Solution

What was wrong with yesterday’s code example? Here it is as a reminder:

Since the developer used the shareReplay operator, the intent was to cache the result of the HTTP request so that we do not make that request repeatedly.

The problem is that if several components call the getData() method, they all get a brand new Observable since the method returns a new request every time, which defeats the purpose of using shareReplay.

How can we fix this? By creating the Observable once then sharing the results in subsequent calls to getData():

Here’s another way to do it, perhaps even more readable:

Why do these solutions work? DataService is a singleton, which means all components use the same instance of DataService. As a result, any property of DataService (such as cache$) is the same for all components that access it.

Another critical thing to note is that HTTP requests are cold observables, which means they only fire when a subscriber subscribes to them.

Code Challenge #1: shareReplay

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:

  1. What do you think is the requirement behind the code in that service? Why use the shareReplay operator?
  2. 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?
  3. 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.