The official Angular doc contains some best practices for effective development but there are other tips that will help you make your application more maintainable and optimized.
Here is a list of my tips and tricks that I use in Angular every day that will help you develop better applications.
When building your application, it’s always useful to reduce side effects like HTTP requests, time-based events, etc.
Abstracting these types of operations from the component to services will reduce the complexity of your components and also ensures the reusability of the services.
A classical example is fetching data from an external server:
import { Component } from "@angular/core";
@Component({
selector: 'app-component',
template: '<ul> <li *ngFor="let item of items">{{item}}</li> </ul>',
})
export class AppComponent implements OnInit{
cats = [];
constructor(private http: HttpClient){
}
getItems(){
return this.http.get('http://apiexample.com/cats')
}
ngOnInit(){
this.getItems.subscribe(cats => this.cats = cats);
}
}
This is a plausible way for displaying a list of items received by a remote endpoint, we have a dedicated method, getItems(), that will make an HTTP GET call and save the result in a local variable.
There’s nothing wrong in this code in terms of functionality, the code does its work and shows the list to the user but the method used in fetching the items is local to the component and can’t be reused, and if items are being fetched in other components, this whole procedure will be repeated.
#javascript #programming #angular