【问题标题】:How Inherit from a baseComponent Angular2?如何从 baseComponent Angular2 继承?
【发布时间】:2017-08-21 19:06:02
【问题描述】:

我正在构建一个 Angular 项目。 我想创建一个具有通用功能的 BaseComponent。 例如:我有一个 TeacherIndexComponent:

@Component({
  selector: 'app-teacher-index',
  templateUrl: './teacher-index.component.html'
})
export class TeacherIndexComponent implements OnInit {
  public teachers : Profesor[];

  constructor(private _otherService: OtherService
              private _teacherService: TeacherService,
              private _messageService : MessageService) {

   }

  ngOnInit() {
   this._otherService.doSomething();

    this._teacherService.getTeachers()
                .subscribe(teacherData => this.teachers= teacherData,
                           error => this._messageService.showErrorMessage(error));

  }

在每个组件中我都必须注入 OtherService。我想创建一个 BaseComponent。在这个组件中应该注入 OtherService 并在它的 ngOnInit() 调用 this._otherService.doSomething(); 这个 baseComponent 没有模板(html)唯一的功能,我需要使用它的事件功能(ngOnInit,ngOnDestroy)。 所有组件都扩展至 BaseComponent:

export class TeacherIndexComponent extends BaseComponent implements OnInit {

BaseComponent 也实现了 OnInit:

export class BaseABMComponent implements OnInit {

  constructor(private _otherService: OtherService) { 
  }

  ngOnInit() {
       this._otherService.doSomething();
  }

这类似于 BaseController,是否可以在 Angular 中构建它?或者我应该在每个组件中重复代码?

非常感谢!

【问题讨论】:

    标签: javascript angular angular-services


    【解决方案1】:

    如果您继承 BaseComponent 并实现自己的 OnInit 以便调用 BaseComponent.ngOnInit 您需要在当前实现的 ngOnInit 方法中调用 super.ngOnInit()(在您的情况下为 TeacherIndexComponent.ngOnInit

    【讨论】:

    • 好的,所以使用 BaseComponent 是不透明的。每个组件都必须在你的 ngOnInit() 中调用 super.ngOnInit() :/
    • 这不是 Angular 的特性。这就是继承在(可能)所有语言(而不是框架)中的工作方式。
    猜你喜欢
    • 2020-01-03
    • 2018-06-03
    • 2018-03-10
    • 2016-06-04
    • 2018-04-12
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多