我有两个名为Member
的打字稿类和另一个abstract
类ComponenetAction
。 ComponentAction
类具有成员实例变量。
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()
之后得到?
答案 0 :(得分:2)
然后member
必须是静态属性才能与其他实例共享:
export abstract class ComponentAction{
static member:Member
constructor(){
}
setMember(member:Member){
ComponentAction.member = member;
}
getMember(){
return ComponentAction.member;
}}