TypeScript父类实例变量返回为undefined

时间:2017-03-26 12:05:48

标签: angular typescript typescript2.0

我有两个名为Member的打字稿类和另一个abstractComponenetActionComponentAction类具有成员实例变量。

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

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

会员班

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

ComponentAction类是我的Angular 2组件类的父类。 LoginComponent类扩展此ComponentAction类并在登录期间设置成员。该成员值设置正确,但我试图从另一个组件类(也扩展ComponentAction)检索相同的成员,我得到'未定义'。

登录组件

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'])
        }
    })
}

}

我试图在DashboardComponent上获取会员信息,因为undefined

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

为什么数据没有在router.navigate()之后得到?

1 个答案:

答案 0 :(得分:2)

然后member必须是静态属性才能与其他实例共享:

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

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