我正在尝试设置一个BehaviourSubject,但它要求为我的类方法提供一个值:
private currentUserSubject = new BehaviorSubject<LoggedInUser>({} as LoggedInUser);
this.currentUserSubject.next(
{
name: decodedJwtData.name,
id: decodedJwtData.id,
isGlobalAdmin: decodedJwtData.isGlobalAdmin === "True",
currentRole: decodedJwtData.currentRole
}
);
这给我一个错误“类型中缺少属性'isAdmin'”
export class LoggedInUser {
name: string;
id: string;
isGlobalAdmin: boolean;
currentRole: string;
isAdmin() {
return this.isGlobalAdmin || this.currentRole == Roles.Owner || this.currentRole == Roles.Administrator;
}
}
该类方法是经过计算的,我应该提供什么?
答案 0 :(得分:1)
可以使用LoggedInUser
获得包含isAdmin()
方法的有效new LoggedInUser()
对象。在当前情况下,您必须提供这样的对象作为BehaviorSubject
的初始值以及next
方法的参数。
您可以使用可选参数定义类构造函数:
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;
}
}
然后可以使用BehaviorSubject
或默认的null
对象初始化LoggedInUser
:
new BehaviorSubject<LoggedInUser>(null);
new BehaviorSubject<LoggedInUser>(new LoggedInUser());
和Behavior.next
方法可通过以下方式调用:
this.currentUserSubject.next(
new LoggedInUser(
decodedJwtData.name,
decodedJwtData.id,
decodedJwtData.isGlobalAdmin === "True",
decodedJwtData.currentRole)
);