是否有可能在角2创建一个组件的抽象? [英] Is it possible to create a Component abstraction on Angular 2?

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

问题描述

我想创建一个AbstractComponent初始行为,同时能够在需要的时候覆盖它的孩子,这可能吗?它是一个好的做法呢?

看起来应该或多或少这样的:

 出口抽象类AbstractComponent实现的OnInit {  构造函数(authService:AuthService,路由器:路由器){}  ngOnInit(){
    如果(authService.userNotLoggedInAnymore()){
      router.navigate(['登录']);
    }
  }  ...
}


解决方案

是的,只是继承了该类与真正的 @Component 并调用超()中的方法你重写,比如ngOnInit。而且你还必须至少在父相同或更多的依赖来覆盖的构造和通过他们超()了。

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

  ...
}

解决方案

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创建一个组件的抽象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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