gpt4 book ai didi

authentication - 通知来自服务的更改的 Angular 2 组件

转载 作者:太空狗 更新时间:2023-10-29 18:16:49 26 4
gpt4 key购买 nike

使用 Angular 2,我有一个处理身份验证的 AuthService。我试图找出在用户登录/注销时通知其他组件的最佳方式,但我不确定处理这种情况的正确方式。有什么建议么?谢谢!

最佳答案

最好的方法是使用BehaviorSubject

class AuthService {

private _isLoggedIn:Subject<boolean> = new BehaviorSubject<boolean>(false);

getUser() {
return !!localStorage.getItem('user');
};

isLoggedIn() {
this.getUser() && this._isLoggedIn.next(true);
!this.getUser() && this._isLoggedIn.next(false);
return this._isLoggedIn.asObservable();
}
}

//在你的组件中

class NavComponent {
constructor(private AuthService: AuthService) {
this.AuthService.isLoggedIn().subscribe(status => this.isLoggedIn = status);
}
}

关于authentication - 通知来自服务的更改的 Angular 2 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41104105/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com