TypeScript parent class instance variable return as undefined

不想你离开。 提交于 2021-01-28 06:29:54

问题


I have two typescript classes named Member and another abstract class ComponenetAction. ComponentAction class has Member as instance variable .

export abstract class ComponentAction{
public member:Member
constructor(){

}
setMember(member:Member){
    this.member = member;
}
getMember(){
    return this.member;
}}

Member class

export class Member{
membername:String
isadmine:String
constructor(name:String,admine:String){
    this.membername = name;
    this.isadmine = admine;
}}

The ComponentAction class is the parent class for my Angular 2 component classes. LoginComponent class extends this ComponentAction class and set the member during login. That member value is set correctly but while i tried to retrieve the same member from another component class(which also extended ComponentAction) am getting 'undefined'.

Login Component

export class LoginComponent extends ComponentAction{
isloggedIn:boolean = true;

constructor(private http :Http , private router:Router){
    super();
}
validate(ngform:NgForm){
    console.log('values :'+ngform.value)
    var user = ngform.value.inputEmail ;
    this.http.post('/api/validate/login', {email:ngform.value.inputEmail,password:ngform.value.inputPassword})
    .map(result => result.json())
    .subscribe((result) => {
        this.isloggedIn = result.isvalid;
        let member = new Member(user,result.isadmine);
        super.setMember(member);
        if(this.isloggedIn){
            this.router.navigate(['./dash'])
        }
    })
}

}

i tried to get the member information in the DashboardComponent am getting it as undefined

export class DashBoardcomponent extends ComponentAction {
user:string;
private sub: any;
constructor(){
    super();
    console.log('dashboard controller super:'+super.getMember());
}}

why the data is not getting after the router.navigate() ?


回答1:


then member must be a static property in order to be shared with other instances :

export abstract class ComponentAction{
static member:Member
constructor(){

}
setMember(member:Member){
    ComponentAction.member = member;
}
getMember(){
    return ComponentAction.member;
}}


来源:https://stackoverflow.com/questions/43028462/typescript-parent-class-instance-variable-return-as-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!