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

二次信任 提交于 2019-12-23 07:00:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!