Async Pipe all the things!

 Async Pipe all the things!. Quick tutorial of how you can easily… | by joaquin cid | Medium


Never .subscribe() again, | async instead

When dealing with Observables in Angular we need to subscribe to them to unwrap the data stream and do what we need to do with each emitted value.

The most common way to this is to:

And on our template:

This pattern requires you to remember to unsubscribe on the ngOnDestroy event to avoid memory leaks and undesired behavior on your app.

You can simplify this by using the async pipe, here’s how it looks like now:

And the template:

Now, the | async is subscribing for us on the template and not only it does that, ¡it automatically unsubscribes for us on the ngOnDestroy event!

How async pipe works

async pipe receives the Observable we define on the template, subscribes to it, and every time it receives a new emission of data it triggers the ChangeDetection cycle to update the view accordingly.

More important, async pipe implements the ngOnDestroy event and unsubscribes from your observable.

You can take a look that the source code here:

Goodbye .unsubscribe()

So now that we know this we can kiss .unsubscribe() goodbye!

If you are wondering how to subscribe to an Observable that you don’t actually want to display data on the template or it doesn’t stream any data, here’s how you can do it.

Let’s consider a FormGroup to which we want to perform an operation every time its value changes.

Instead of subscribing to it, we can | async to it inside an ng-container. This way we wont need to subscribe and unsubscribe to the Observable without also displaying any data in the page.

Conclusion

We’ve learned how to use the async pipe to subscribe to any Observable on Angular, and how this eliminates the need to unsubscribe from it.


Không có nhận xét nào:

StaticImage

  import React , { useEffect , useRef } from "react" import { StaticImage } from "gatsby-plugin-image" impor...