Laurie Atkinson, Senior Consultant, By moving shared functionality to a base component and assigning dependencies inside the body of the constructor, you can simplify child components.
If your Angular components contain identical or similar functionality and you find yourself copying and pasting that code, it makes sense to implement some class inheritance, which is available with TypeScript. And, you can simplify the child components even further by removing the dependencies from the parent constructor arguments and manually assigning them inside the constructor.
Create the base component
In this example, we have 2 services that are used in the base class and are assigned using dependency injection.
base.component.ts
@Component({
template: ''
})
export class BaseComponent {
constructor(protected utilitiesService: UtilitiesService,
protected loggingService: LoggingService) {
this.logNavigation();
}
protected logError(errorMessage: string) { . . .}
private logNavigation() { . . .}
}
Inherit child component from base component
Note that our child component must pass all parent dependencies into the constructor to extend it.
child.component.ts
@Component({ . . . })
export class ChildComponent extends BaseComponent {
constructor(private childDataService: ChildDataService,
utilitiesService: UtilitiesService,
loggingService: LoggingService) {
super(utilitiesService, loggingService);
}
}
As you can see, with a substantially complex base class, the child classes will potentially need to include a much longer list of all its parent’s dependencies. And if the parent introduces a new dependency, then all children must be updated. This may be fine, but if you want to simplify the child classes as much as possible, then take a look at this alternative.
Use a class to store the injector
This class will hold the module’s injector. It will be set once and retrieved whenever a component or service needs to get a service dependency.
app-injector.service.ts
import { Injector } from '@angular/core';
export class AppInjector {
private static injector: Injector;
static setInjector(injector: Injector) {
AppInjector.injector = injector;
}
static getInjector(): Injector {
return AppInjector.injector;
}
}
After the module has been bootstrapped, store the module’s injector in the AppInjector class.
main.ts
platformBrowserDynamic().bootstrapModule(AppModule).then((moduleRef) => {
AppInjector.setInjector(moduleRef.injector);
});
Use this injector class to assign dependencies
Now, we can modify the base component to remove all constructor arguments.
base.component.ts
@Component({
template: ''
})
export class BaseComponent {
protected utilitiesService: UtilitiesService;
protected loggingService: LoggingService;
constructor() {
// Manually retrieve the dependencies from the injector
// so that constructor has no dependencies that must be passed in from child
const injector = AppInjector.getInjector();
this.utilitiesService = injector.get(UtilitiesService);
this.loggingService = injector.get(LoggingService);
this.logNavigation();
}
protected logError(errorMessage: string) { . . . }
private logNavigation() { . . . }
}
Inherit child component from base component
Now the child component only needs to use dependency injection for its own dependencies.
child.component.ts
@Component({ . . . })
export class ChildComponent extends BaseComponent {
constructor(private childDataService: ChildDataService) {
super();
}
}
Use the power of polymorphism to maximize code reuse
For maximum reuse of code, do not limit the methods in the parent class to merely those with identical implementations. Maybe you can refactor a complex method into pieces where shared logic can be moved into the parent. Maybe a method shares most of the logic with another component, but a few pieces differ between components which could be implemented in each child.
TypeScript inheritance allows you to override a parent method in the child class and if the parent calls that method, the child’s implementation will be invoked. For example, follow the order of execution shown in this picture, starting with a call to methodA() in ChildComponent.
Here is a non-trivial code example to illustrate the power of this feature. This application contains many pages, each comprised of a form. All these form pages share the following functionality:
- only allow editing if the user has permission
- save changes via a call to an API service
- prompt the user if attempting to navigate away and there are unsaved changes
Build a form base component
form.component.ts
@Component({
template: ''
})
export class BaseFormComponent extends BaseComponent implements OnInit {
updatePermission = 'UPDATE_FULL'; // Can override in child component
protected routeParamName: string; // value always set in child
protected entity: IEntity; // data on the form
protected original: IEntity; // data before any changes are made
protected dataService: EntityDataService; // service with http methods
protected updateService: UpdateService;
protected authorizationService: AuthorizationService;
@ViewChild('confirmationDialog') confirmationDialog: ConfirmDialogComponent;
constructor(protected route: ActivatedRoute) {
super(); // call parent constructor
const injector = AppInjector.getInjector();
this.updateService = injector.get(UpdateService);
this.authorizationService = injector.get(AuthorizationService);
}
ngOnInit() {
this.route.data.subscribe(data => { // data from route resolver
this.entity = data[this.routeParamName]; // routeParamName from child
. . .
this.additionalFormInitialize(); // optional initialization in child
});
}
protected additionalFormInitialize() { // hook for child
}
// Child could override this method for alternate implementation
hasChanged() { return !UtilitiesService.isEqual(this.original, this.entity); }
// used by canDeactive route guard
canDeactivate() {
if (!this.hasChanged()) {
return true;
}
return this.showConfirmationDialog().then(choice => {
return choice !== ConfirmChoice.cancel;
});
}
showConfirmationDialog() {
return new Promise((resolve) => {
this.confirmationDialog.show();
. . .
this.save().then(() => {
. . .
}, (err) => {
this.logError(err); // Implemented in base parent component
});
});
}
save() {
// Value of dataService set in the child to support different APIs
// Optionally override saveEntity in the child
return this.updateService.update(this.dataService, this.saveEntity).then( . . .
}
protected get saveEntity() { return this.entity; }
// Use in child HTML template to limit functionality
get editAllowed() { // updatePermission could be overridden in the child
return this.authorizationService.hasPermission(this.updatePermission);
}
}
Build a specific form child component
child.component.ts
@Component({. . .})
export class ChildComponent extends BaseFormComponent {
updatePermission = 'CHILD_UPDATE'; // can override the default permission
protected routeParamName = 'child'; // required by parent to read route data
constructor(private childDataService: ChildDataService) {
super();
}
protected get dataService() { return this.childDataService; }
protected get saveEntity() {
// perhaps do some custom manipulation of data before saving
return localVersionOfEntity;
}
protected additionalFormInitialize() {
// Add custom validation to fields or other unique actions
}
hasChanged() {
// Could override this method to implement comparison in another way
}
}
As you proceed with your development, if you find yourself copying and pasting code, take a moment to see if some refactoring might be in order. Class inheritance can give you an opportunity to delete some code and that always feels good. Doesn’t it?
This is a neat trick. It even works, until I run the unit test cases. Apparently, the injector or the services doesn’t get initialized before the component constructor get’s called. I’m using the replaysubject method: AppInjector.getInjector().pipe(take(1)).subscribe((injector) => { this.authService = injector.get(AuthService); }); in BaseComponent and when the child component calls the method: this.authService.isLoggedIn(); the unit test case fails, saying authservice is undefined.
Two points about this kind of inheritance...
1. Just inject the injector and angular will do all the work for you, and even make sure you get the right injector if your module is lazy loaded
... BaseComponent {
constructor(injector: Injector) {
}
}
2. Inheritance of anything other than simple components has some gotchas because the decorators do not get extended, and lifecycle hoooks...
Is there a proper way to do this with an abstract Service as well? Seems like services will require a different kind of magic…
Why use the @Component decorator if you’re not utilizing the template. This can be done with standalone classes.
Hi Laurie,
l liked the post and implmented as you described, but I have an intermintent timing issue. In main.ts the call to: platformBrowserDynamic().bootstrapModule(AppModule).then((moduleRef) => {
AppInjector.setInjector(moduleRef.injector);
});
is not always called before the base component constructor is called.
constructor(protected route: ActivatedRoute) {
super();
// call parent constructor
const injector = AppInjector.getInjector();
this.updateService = injector.get(UpdateService);
this.authorizationService...
Instead of calling .setInjector() after resolving the bootstrapModule promise, move the .setInjector() method to the constructor of AppModule:
export class AppModule { constructor(injector: Injector) { AppInjector.setInjector(injector); }}That should do the trick.Thanks to: https://stackoverflow.com/a/43695820/1513172
Mr Roy and Mr Criss with comment thanks a lot! Also thanks for this awesome article, GREAT STUFF!
Great…that works..
You can make AppInfo.getInjector() returning an Rx.ReplaySubject<Injector>:
export class AppInjector { private static injector: Injector = undefined; private static subject = new ReplaySubject<Injector>();static setInjector(injector: Injector) { console.log('SET INJECTOR'); AppInjector.injector = injector; AppInjector.subject.next(AppInjector.injector); }static getInjector(): ReplaySubject<Injector> { console.log('READING INJECTOR'); return AppInjector.subject; }}
Then, in your Components Constructor subscribe to that Subject and wait for the Injector:
AppInjector.getInjector() .pipe(take(1)) .subscribe((injector) => { this.dialogService = injector.get(DialogService); this.routerService = injector.get(Router); });