0

I am building a angular project. I want to create a BaseComponent with common functionality. For example: I have a 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));

  }

In every components I have to inject OtherService. I want to create a BaseComponent. In this component should inject OtherService and in its ngOnInit() call to this._otherService.doSomething(); This baseComponent has not a template (html) only functions, I need to use its events functions (ngOnInit, ngOnDestroy). All component extends to BaseComponent:

export class TeacherIndexComponent extends BaseComponent implements OnInit {

and BaseComponent implement OnInit too:

export class BaseABMComponent implements OnInit {

  constructor(private _otherService: OtherService) { 
  }

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

This is similar to BaseController, Is possible build it in Angular ? Or I should repeat code in every component ?

Thanks very much!

1 Answers1

1

If you inherit BaseComponent with implementing own OnInit in order to call BaseComponent.ngOnInit you need to call super.ngOnInit() inside currently implemented ngOnInit method (in your case TeacherIndexComponent.ngOnInit)

be4code
  • 688
  • 4
  • 15