是维护全局变量angular2
的最佳途径。我无法找到一种通过应用程序来维护全局变量的方法。用户登录到应用程序后,我需要User
对象,它在所有其他组件的用户资料和isLoggedIn
值。下面是我在做什么...角2个像isLoggedIn全局变量或
@Injectable()
export class AppGlobals {
public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public currentUser: BehaviorSubject<User> = new BehaviorSubject<User>(null);
setLoginStatus(isLoggedIn) {
this.isUserLoggedIn.next(isLoggedIn);
}
setCurrentUser(currentUser) {
this.currentUser.next(currentUser);
}
}
在loginComponent我在成功登录
login() {
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(
data => {
this.appGlobals.setLoginStatus(true);
this.appGlobals.setCurrentUser(data);
this.router.navigate([this.returnUrl]);
},
error => {
this.alertService.error(error);
this.loading = false;
});
}
建立user
和isLoggedIn
细节和其他组件访问值....
export class ProductsComponent {
currentUser: User;
isLoggedIn: boolean;
constructor(private productService: ProductService, private router:Router,
private confirmationService: ConfirmationService,
private auth: AuthenticationService,
private appGlobal: AppGlobals) {
appGlobal.isUserLoggedIn.subscribe(value => {this.isLoggedIn = value; console.log(value);}); // should be true
appGlobal.currentUser.subscribe(value => {console.log(value); this.userRole = value}); // should have user data
.....
}
.....
}
在ProductsComponent
isLoggedIn
和currentUser
的值是第一次正确,但是当我刷新了浏览器false for isLoggedIn
和null for user
。不知道我在做什么错,在哪里。维护所有组件的用户和登录状态是完全错误的吗?我不想跟sessionStorage
或localStorage
一起去。请建议。谢谢。
当你刷新,临时存储(分配)被擦除!所以你不应该刷新你的浏览器!或者你可以选择缓存吧'document.cache' – Smit
@Smit感谢您的信息,我不知道它会删除数据 – user1653027