是否可以在Angular 2上创建组件抽象?

Mar*_*hel 13 architecture abstraction angular

我想创建一个具有初始行为的AbstractComponent,同时能够在需要时覆盖它,可能吗?这是一个好习惯吗?

应该看起来或多或少那样:

export abstract class AbstractComponent implements OnInit {

  constructor(authService: AuthService, router: Router) {}

  ngOnInit() {
    if (authService.userNotLoggedInAnymore()) {
      router.navigate(['Login']);
    }
  }

  ...
}
Run Code Online (Sandbox Code Playgroud)

Lan*_*ley 13

是的,只需使用real扩展该类,@Component并调用super()您覆盖的方法,如ngOnInit.而且您还必须覆盖父级中至少具有相同或更多依赖项的构造函数,并将其传递给它们super().

  • 使用--aot构建Angular 4应用程序时出错:"ERROR in无法确定[file]中类[MyComponent]的模块!将[MyComponent]添加到NgModule中进行修复." 任何人都有解决方法吗? (5认同)
  • 组件继承不包括模板和样式. (3认同)
  • 模板怎么样,也可以用父抽象组件嵌套? (2认同)