Refetching Data with RxJS Subjects in Angular

2 min read
Share:

One of the things that drove me crazy when I was first learning RxJS in Angular was how difficult it seemed to reload a collection of data after I added or deleted an item. With promises, I could just use .then() and be on my way. What do we do with observables? Should we just nest another subscription? Even if we do that, since we’re using the async pipe, nothing will happen. There are better ways to handle this that are more reactive. In this lesson, I’m going to show you one way using Subjects. Subjects are kind of like event emitters that can have multiple listeners.

A few vocab words I mention in this video:

  • Subject: A special type of Observable that allows values to be multicasted. Think of it like an event emitter that allows multiple listeners.
  • BehaviorSubject: A type of Subject that stores its latest value.
  • tap operator: Performs a side effect for every emission of its source Observable.
  • switchMap operator: Maps each value to an Observable, then flattens all of these inner Observables.

Check out the code on GitHub to see the result.

Want more tutorials?

I write about building with modern tools and frameworks. Subscribe to get practical tutorials and deep dives delivered to your inbox.

Related Articles

How to Use Route Parameters in Angular

We often need to pass a parameter like an ID to a route and then access that ID in order to call an API to get some data. In this article, we'll look at how to define a route with a parameter, how to use params with the routerLink directive, and how to use the route snapshot to use a param in a component.