3 Powerful Tips to Improve Angular Codebases | by Vladimir Topolev | Jan, 2022

Some ways to improve the quality of your Angular apps

Vladimir Topolev
Photo by Thought Catalog on Unsplash

When you declare a new dependency via factory you may end up with the following code:

function loggerFactory(service1: Service1, service2: Service2) {
// skipped for brevity
}
@Component({
//... skipped
providers: [{
provide: LoggerService,
useFactory: loggerFactory,
deps: [Service1, Service2]
}]
})
function loggerFactory(injector: Injector){
const service1 = injector.get(Service1);
const service2 = injector.get(Service2);
// skipped for brevity
}
@Component({
//... skipped
providers: [{
provide: LoggerService,
useFactory: loggerFactory,
deps: [Injector]
}]
})

Let’s have a look at a simple directive, which just changes the color of an element. Code may look like that:

@Directive({
selector: [appBasicDirective]
})
export class BasicDirective implements OnInit {
constructor(private elRef: ElementRef) {}
ngOnInit() {
this.elRef.nativeElement.style.backgroundColor = 'green'
}
}
@Directive({
selector: [appBasicDirective]
})
export class BasicDirective implements OnInit {
constructor(
private elRef: ElementRef,
private renderer: Renderer2
) {}
ngOnInit() {
this.renderer.setStyle(
this.elRef.nativeElement,
'background-color', 'green'
);
}
}

During development, we should not forget to unsubscribe from Observables that are used in a component; otherwise we may end up with memory leaks:

export Component implements OnDestroy {

private subscription1 = observable1$.subscribe(...);
private subscription2 = observable2$.subscribe(...);

ngOnDestroy() {
this.subscription1.unsubscribe();
this.subscription2.unsubscribe();
}
}
export Component implements OnDestroy {
private subs = new SubSink();

this.subs.sink = observable1$.subscribe(...);
this.subs.sink = observable2$.subscribe(...);

ngOnDestroy() {
this.subs.unsubscribe();
}
}

Leave a Comment