Mic*_*win 3 authentication typescript angular
使用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();
}
}
Run Code Online (Sandbox Code Playgroud)
//在您的组件中
class NavComponent {
constructor(private AuthService: AuthService) {
this.AuthService.isLoggedIn().subscribe(status => this.isLoggedIn = status);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
519 次 |
| 最近记录: |