是否可以在 Angular 2 上创建组件抽象? [英] Is it possible to create a Component abstraction on Angular 2?

查看:25
本文介绍了是否可以在 Angular 2 上创建组件抽象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 扩展该类并在方法中调用 super()你覆盖,比如 ngOnInit.而且您还必须在父级中使用至少相同或更多的依赖项覆盖构造函数,并使用 super() 传递它们.

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.

这篇关于是否可以在 Angular 2 上创建组件抽象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆