Code Reuse in Angular with Object Composition & Inheritance
Code examples of object composition & inheritance in Angular
Based on my story Inheritance & Object Composition I want to show, how we can use some Angular features for reusing code in really nice ways. I prepared some easy examples below.
Inheritance
Inheritance is a straightforward principle in Angular. We can combine a base class with a superclass by using the extends term. The superclass inherits fields and methods from the base class.
Subscribing and unsubscribing to an observable in a Redux store is a common repeatable practice. We can DRY, when we separate this logic in a base class.
// base.component.ts
export class BaseComponent implements OnInit, OnDestroy {
public randomNumber: number;
private selectNumber$: Observable<number>;
private subNumber: Subscription;
private destroyer$: Subject<void>;
constructor(protected store: Store<State>) {
this.destroyer$ = new Subject<void>();
}
ngOnInit(): void {
this.subscribeToRandomNumber();
}
ngOnDestroy(): void {
this.unsubscribeNumber();
}
public getRandomNumber() {
this.store.dispatch(GetRandomNumber());
}
protected subscribeToRandomNumber(): void {
this.selectNumber$ =…