Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 错误类型错误:";x为空”;从应用程序注销时_Angular_Typescript_Authentication - Fatal编程技术网

Angular 错误类型错误:";x为空”;从应用程序注销时

Angular 错误类型错误:";x为空”;从应用程序注销时,angular,typescript,authentication,Angular,Typescript,Authentication,在我的应用程序中。我使用这个示例实现身份验证。我得到一个错误TypeError:“x为空”。当我实现注销功能时。问题可能是什么,我如何解决它。请引导我 我在多个组件中使用isCurrentUserAdmin方法来检查用户是否为admin authenticationService.ts private userSubject: BehaviorSubject<User>; public user: Observable<User>; isCurrentUserAdmi

在我的应用程序中。我使用这个示例实现身份验证。我得到一个错误TypeError:“x为空”。当我实现注销功能时。问题可能是什么,我如何解决它。请引导我

我在多个组件中使用isCurrentUserAdmin方法来检查用户是否为admin

authenticationService.ts

private userSubject: BehaviorSubject<User>;
public user: Observable<User>;

 isCurrentUserAdmin(): boolean {
    this.user.subscribe(x => this.currentUserRole = x.role);
    return this.user && this.currentUserRole === Role.admin;
  }


  logout() {
    // remove user from local storage to log user out
    this.deleteToken();
    this.userSubject.next(null);
    this.router.navigate(['/login']);
  }
私有用户主体:行为主体;
公共用户:可观察;
isCurrentUserAdmin():布尔值{
this.user.subscribe(x=>this.currentUserRole=x.role);
返回this.user&&this.currentUserRole===Role.admin;
}
注销(){
//从本地存储中删除用户以注销用户
this.deleteToken();
this.userSubject.next(null);
this.router.navigate(['/login']);
}

您向
userSubject
发送一个
null
(当然
user
也会收到)。现在,在
isCurrentUserAdmin
中,您尝试访问
user
的属性,但此时
user===null
,它不再具有该属性(
角色

您需要过滤空用户(实际上我不会将订阅放在该函数中,因为每次调用该函数时您都会创建一个新的订阅)

this.user.pipe(过滤器(x=>x!==null)).subscribe(x=>this.currentUserRole=x.role)

现在,如前所述,将订阅放在只调用一次的其他地方。此外,还要确保在组件被销毁时取消订阅。在这种情况下,可能不需要它,因为可观察的对象在同一个组件中,并且会一起被破坏(我认为),但这是一个好习惯

编辑:
实际上,当用户设置为null时,您可能应该取消订阅,因为从技术上讲,即使用户为null,您仍然拥有一个角色。(您可以使用
this.user
在返回中防止这种情况,但这仍然是一种错误的逻辑。)
当用户被设置时订阅,当用户被清除时取消订阅时,您可能不需要过滤器

编辑2:
我不太确定性能(取决于您调用函数的频率),但您也可以直接从用户可观察到的角色:

return this.user.pipe(take(1)).subscribe(x => x ? x.role : null);
当您注销时,用户变为空
因此x为null,因此访问x.role会引发错误

和@Gunnar B.的解决方案,不建议对其进行过滤
因为此.currentUserRole必须用User或else更新
当用户注销时,他们仍将扮演前一个用户的角色。

能否替换此.userSubject.next(null);使用此.userSubject.next()?
isCurrentUserAdmin(): boolean {
    this.user.subscribe(x => this.currentUserRole = x ? x.role : null);
    return this.user && this.currentUserRole === Role.admin;
}