问题
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']);
}
}
...
}
回答1:
Yes, just extend that class with the real @Component
and call super()
in the methods you override, like ngOnInit. And you also have to override the constructor with at least the same or more dependencies in the parent and pass them with super()
too.
回答2:
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']);
}
}
...
}
来源:https://stackoverflow.com/questions/34752288/is-it-possible-to-create-a-component-abstraction-on-angular-2