Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a Component abstraction on Angular 2?

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']);
    }
  }

  ...
}
like image 682
Marcos J.C Kichel Avatar asked Jan 12 '16 19:01

Marcos J.C Kichel


People also ask

What is component abstraction?

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.

What is abstraction in angular?

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.

What is inheritance in angular?

“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.


1 Answers

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']);
    }
  }
  ...
}
like image 162
Mike Avatar answered Oct 05 '22 06:10

Mike