4 mistakes I have made while learning Angular and RXJS

Olena Liebiedieva
2 min readMay 4, 2019

--

Let me share a few mistakes I have made while learning Angular and RXJS.

I. πŸ‘Ž Using async pipe for the same async source several times within one component template

<div>
<img [src]="asyncImgSrc | async" />
</div>
...
<div>
<img [src]="asyncImgSrc | async" />
</div>

In this case template will subscribe twice on asyncImgSrc, so if we have http call there it will provoke two http requests β€” thas is not good, I guess.

πŸ‘ How to solve: use ng-template, ng-container with context definition and ngTemplateOutlet:

<ng-template #layout let-src="src">
<div>
<img [src]="src" />
</div>
...
<div>
<img [src]="src" />
</div>
</ng-template>
<ng-container
*ngTemplateOutlet="layout; context: {src: asyncImgSrc | async}">
<ng-container>

II. πŸ‘Ž Forgotten unsubscribe from observables

πŸ‘ How to solve: RXJS takeUntil operator placed last in every pipe with some subject as a parameter that gets next value when component has been destroyed is a very nice solution. Good links about this topic are: Stackoverflow answer and Angular In Depth blog.

III. πŸ‘Ž Using getters for in-template binding

There is an interesting conversation about such approach at Angular GitHub. I tried the example: adding simple loop in the getter froze Chrome forever πŸ˜„. Even OnPush Change Detection Strategy does not solve a problem. But the recommendation that is given by above link πŸ‘ does:

never bind to functions if it can be avoided.

I learned it from my team lead: we can’t know how our code will grow, so letting things simple can save us from problems.

IV. πŸ‘Ž Direct DOM changes

this.element.nativeElement.innerHtml = ...

Stop. I heard: β€œstop!”. What is temptation to do this way after Angular.js!

Team lead just used createEmbeddedView instead πŸ‘ and avoided uncotrolled behaviour of new markup. No words.

This short note frees my head from excess information and prevent me from repeating mistakes in future. Will think more 😏. Thank you for reading.

--

--