Angular 6 BehaviourSubject.next要求类方法的值

时间:2018-08-30 01:57:22

标签: angular typescript rxjs

我正在尝试设置一个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;
    }
}

该类方法是经过计算的,我应该提供什么?

1 个答案:

答案 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)
);