[英]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. 顺便说一句,此代码按预期工作。
super
is used to send arguments to the base class constructor from the derived class. super
用于从派生类将参数发送到基类构造函数。 If this was your confusion, it is the right way. 如果这是您的困惑,那是正确的方法。
(perhaps this is the only use for the super
keyword!) (也许这是super
关键字的唯一用法!)
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. 同样,如果不给定修饰符(如public
或private
,则可以接受不属于给定类的参数。 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, 本质上, modifier
创建一个新的类元素classVar
,并将提供给构造函数的参数classVar
分配给this.classVar
即,
class Sample {
classVar: number;
constructor(classVar : number) {
this.classVar = classVar
}
would be equivalent to 相当于
class Sample {
constructor(public classVar : number) {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.