I want to create a AbstractComponent with initial behavior while being able to override it on child when needed, is it possible? Is it a good practice?
Should look more or less like that:
export abstract class AbstractComponent implements OnInit {
constructor(authService: AuthService, router: Router) {}
ngOnInit() {
if (authService.userNotLoggedInAnymore()) {
router.navigate(['Login']);
}
}
...
}
Component abstraction is a technique that groups related low-level constants of a planning problem into more abstract entities called abstract components or, shorter, components. The idea is similar to how humans can group features connected through static relationships into one more abstract unit.
So you use Typescript classes for coding Angular / React projects, but do you know what are abstract classes in typescript? Abstract classes are mainly for inheritance where other classes may derive from them. We cannot create an instance of an abstract class.
“Inheritance” in object-oriented programming describes the relationship between a parent class and one or more children. A “child” object “extends” its parent and “inherits” its features. The child can do everything the parent can do while also declaring functions/properties of its own.
As an alternative you can also do without the constructor parameters in the abstract class at all and declare the services with the @Inject decorator, then you don´t need to touch the constructor of the inheriting class and call the super(...)-method there:
import { Inject } from '@angular/core';
export abstract class AbstractComponent implements OnInit {
@Inject(AuthService) private authService: AuthService;
@Inject(Router) private router: Router;
ngOnInit() {
if (authService.userNotLoggedInAnymore()) {
router.navigate(['Login']);
}
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With