3 best practices in Angular to make your Single Page Applications Fast, Secure, and Scalable
By Vikipediaaaa
Website: Vikas Saraf
Most of us developers have been there when we feel that if it works, don't touch it. Well to some extent it might be good, but definitely not always. Surely, to make something work is a developer's job, but to make something work better is a sign of a good developer.
We all want to be called a "good" developer in the Dev community, heck even a "best" developer. If you work in Angular, say no more, I have got you covered.
I will write about 3 practices of the industry that one should implement in their Angular Single Page Applications or (SPAs). So without further ado, here we go :
## Avoiding logic in templates :
Many a time we feel that a simple logic such as a simple && clause, or || clause should be done in the template itself. Well, this might seem convenient at the time and saves a couple of minutes but leaves the code bug-prone. Also, writing logic in the template means it is not possible to write unit test cases for the logic.
WE DONT want to do that, do we?
So, a simple solution is to extract as much logic as possible from the template to its component.
What we do :
Explanation: We are comparing the role variable with a string value i.e "developer" directly in the template itself.
What we should do instead :
Explanation: We are assigning a boolean variable (this.showDeveloperStatus) with value as true which in turn is checked by *ngIf in the template, thus extracting all the logic from the template.
## Adding Caching Mechanisms :
In order to GET data, we always make API calls from a remote server. The response from the server may be fast or maybe slow, also the amount of data might be huge or insignificant. But if are aware and know that some of the data might not change often, then we can implement a caching mechanism and store the response from the API.
For example, you can check if there is a value in the cache when sending another request to the same API. If it is available, you can use it, otherwise, you can make the API call and cache that result.
If the values change but not frequently, you can introduce a cache time where you can check when it was last cached and decide whether or not to call the API. The speed of the application improves as we do not have to wait for the network. It also means we do not download the same information over and over again.
## Pipeable Operators :
Use pipeable operators when using RxJs operators.
Pipeable operators are tree-shakeable meaning only the code we need to execute will be included when they are imported.
This also makes it easy to identify unused operators in the files.
Note: This needs Angular version 5.5+.
What we do:
What we should do instead:
Thank you for reading!
If you enjoyed this article, please feel free to share it and help others find it. Follow me Vikipediaaaa for more articles. Happy coding folks!! ☕️