Beetlejuice
Beetlejuice

Reputation: 4425

Typescript class inheritance

I'm not sure if I'm doing the right thing here. I need to create a base class, so that my controls can inherit from it. So I did this base class:

import { Location } from '@angular/common';

export class FormBaseComponent  {
  constructor(
    protected location: Location
  ) {}

  goBack() {
    alert('back');
    this.location.back();
  }

}

and a class that inherit from it:

import { Component, OnInit } from '@angular/core';
import {
  FormBuilder
} from '@angular/forms';
import { UserService } from 'app/shared/services/user/user.service';
import { User } from 'app/models/authentication/user';
import { Router } from '@angular/router';
import { Location } from '@angular/common';
import { FormBaseComponent } from 'app/shared/components/form-base.component';

@Component({
  selector: 'app-my-account',
  templateUrl: './my-account.component.html',
  styleUrls: ['./my-account.component.scss']
})
export class MyAccountComponent extends FormBaseComponent implements OnInit  {
  formEdit = this.fb.group(User.formGroup());

  constructor(
    private fb: FormBuilder,
    private userServices: UserService,
    private router: Router,
    location: Location
  ) {
    super(location);
  }

  ngOnInit() {
    this.userServices.getCurrentUser().subscribe( x => {
      this.formEdit.patchValue(x);
    });
  }

  onSubmit() {
    this.userServices.update(this.formEdit.getRawValue()).subscribe( x => {
      this.router.navigate(['/']);
    });
  }

}

Is it correctly to declare this "location" parameter in the constructor like this?

  location: Location
) {
  super(location);
} 

BTW, this code works as expected.

Upvotes: 0

Views: 164

Answers (1)

Dhananjai Pai
Dhananjai Pai

Reputation: 6005

super is used to send arguments to the base class constructor from the derived class. If this was your confusion, it is the right way.

(perhaps this is the only use for the super keyword!)

Also, if you dont give a modifier like public or private you can take arguments that do not form a part of the given class. So your code is indeed the way it is supposed to work.

essentially the modifier creates a new class element classVar and assigns the argument classVar supplied to constructor to this.classVar ie,

class Sample {
    classVar: number;
    constructor(classVar : number) {
         this.classVar = classVar
    }

would be equivalent to

class Sample {
    constructor(public classVar : number) {
    }

Upvotes: 2

Related Questions