Angular 角度6.下一步为类方法询问值
我试图设置一个行为主题,但它要求为我的课堂方法设置一个值:Angular 角度6.下一步为类方法询问值,angular,typescript,rxjs,Angular,Typescript,Rxjs,我试图设置一个行为主题,但它要求为我的课堂方法设置一个值: private currentUserSubject = new BehaviorSubject<LoggedInUser>({} as LoggedInUser); this.currentUserSubject.next( { name: decodedJwtData.name, id: decodedJwtData.id, isGlobalAdmin: deco
private currentUserSubject = new BehaviorSubject<LoggedInUser>({} as LoggedInUser);
this.currentUserSubject.next(
{
name: decodedJwtData.name,
id: decodedJwtData.id,
isGlobalAdmin: decodedJwtData.isGlobalAdmin === "True",
currentRole: decodedJwtData.currentRole
}
);
类方法已计算,我应该为其提供什么?可以使用新的LoggedInUser获得包含isAdmin方法的有效LoggedInUser对象。在本例中,必须提供这样一个对象作为BehaviorSubject的初始值,并作为下一个方法的参数
可以使用可选参数定义类构造函数:
export class LoggedInUser {
constructor(
public name?: string,
public id?: string,
public isGlobalAdmin?: boolean,
public currentRole?: string) {}
isAdmin() {
return this.isGlobalAdmin || this.currentRole == Roles.Owner || this.currentRole == Roles.Administrator;
}
}
然后,可以使用null或默认LoggedInUser对象初始化BehaviorSubject:
export class LoggedInUser {
constructor(
public name?: string,
public id?: string,
public isGlobalAdmin?: boolean,
public currentRole?: string) {}
isAdmin() {
return this.isGlobalAdmin || this.currentRole == Roles.Owner || this.currentRole == Roles.Administrator;
}
}
new BehaviorSubject<LoggedInUser>(null);
new BehaviorSubject<LoggedInUser>(new LoggedInUser());
this.currentUserSubject.next(
new LoggedInUser(
decodedJwtData.name,
decodedJwtData.id,
decodedJwtData.isGlobalAdmin === "True",
decodedJwtData.currentRole)
);