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 Answer 1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, so using BaseComponent isn't transparent. Every component must call super.ngOnInit() in your ngOnInit() :/
It is not a Angular's feature. That is how inheritance works in (probably) all languages (not frameworks).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.