2017-03-02 78 views
1
的UserRole什麼

是維護全局變量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; 
     }); 
} 

建立userisLoggedIn細節和其他組件訪問值....

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 
     ..... 
    } 
    ..... 
} 

ProductsComponentisLoggedIncurrentUser的值是第一次正確,但是當我刷新了瀏覽器false for isLoggedInnull for user。不知道我在做什麼錯,在哪裏。維護所有組件的用戶和登錄狀態是完全錯誤的嗎?我不想跟sessionStoragelocalStorage一起去。請建議。謝謝。

+1

當你刷新,臨時存儲(分配)被擦除!所以你不應該刷新你的瀏覽器!或者你可以選擇緩存吧'document.cache' – Smit

+1

@Smit感謝您的信息,我不知道它會刪除數據 – user1653027

回答

0

你爲什麼不使用localStorage的

當你登錄你設定的localStorage的

localStorage.setItem('currentUser', JSON.stringify({ email: email, id: id })); 

需要在檢查中記錄的localStorage的

localStorage.getItem('currentUser') 

和用戶的任何組件註銷

localStorage.removeItem('currentUser'); 
+1

我從別人知道,有在'sessionStorage'爲userDetails或'localStorage'是不是一個最好的方法,所以想用'全局變量'去......我只是提出建議,因爲它已經三個星期了,我開始學習Angular2 – user1653027

+0

只是想澄清一下'localStorage'是否有任何我們可以清除'localStorage'每當我們重新啓動應用程序? – user1653027

+0

這就是我提到的最後一次調用removeItem的做法 –

0

只需使用您在AppModule提供的服務。它將是一個單例,可在整個應用程序中使用,並且與Angular應用程序具有相同的生命週期。

每個組件,指令,管道和服務可以注入它來訪問其狀態或訂閱它的觀測。