2017-03-21 59 views
2

我有一個登錄組件控制登錄頁面和警報(成功,錯誤,信息...)。例如,當我在頁面中時,我可以顯示警報而不會出現問題,例如通知用戶無效憑據或通知頁面正在更新。基本上,這消息是綁定到前端的登錄組件類變量:註銷用戶提醒消息

export class Login { 
    error; 
    info; 
} 

現在,當用戶註銷我重定向到登錄頁面:

this.router.navigate(['/login']); 

我想顯示一個警告用戶通知註銷過程是成功的(實際上,我將使用相同的邏輯來通知用戶會話是否過期)。我在登錄組件類中創建了兩種方法:

logout() { 
    this.authenticationService.logout() 
     .subscribe(response => { 
      this.logoutRedirect(); 
     }, 
     error => { 
      this.logoutRedirect(); 
     }); 
    } 

    logoutRedirect() { 
     this.authenticationService.removeUser(); 
     this.info = 'Logout success'; 
     this.router.navigate(['/login']); 
    } 

除消息之外的所有東西都有效。我相信這是因爲當用戶重定向時使用了一個新的登錄類,而這個登錄類沒有信息信息。

這個問題的最佳方法是什麼:我會在我的應用程序中使用它,所以我想正確地做到這一點。

回答

0

我使用服務解決了這個問題。該服務具有由警報組件訂閱的BehaviorSubject。基本上是:

export class AlertMessagesService { 

public alertStatus: BehaviorSubject<AlertMessage>; 

public addAlert(msg: string = null, type: string = 'info') { 
    this.alertStatus.next({ 
     show: true, 
     msg: msg, 
     type: type 
    }); 
} 

} 

這裏是在警報顯示組件:

export class AlertMessages implements OnInit { 

alerts: Array<AlertMessage> = []; 

constructor(
    private alertService: AlertMessagesService) { 
} 

ngOnInit() { 

    this.alertService.alertStatus.subscribe((alert: AlertMessage) => { 

     if(alert.show) { 
      this.alerts.push(alert); 
     } 

    }); 

} 

} 

我希望它能幫助,如果有人碰到這種情況。