fred00
fred00

Reputation: 611

Logout user with alert message

I have a login component that controls the login page and alerts (success, error, information,...). I can display alerts with no problems when I am in the page, for instance, to inform the user invalid credentials or to inform that the page is being updated. Basically this messages are variables in the login component class binded to the frontend:

export class Login {
  error;
  info;
}

Now when the user logouts I redirect to the login page:

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

I want to show an alert to the user informing the logout process was successful (actually I will use this same logic to inform if the user session expires). I created two methods in login component class:

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

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

Everything works except the message. I believe it happens because when the user is redirected a new login class is used and this one does not have the info information.

How is the best approach for this problem: I will use it a lot in my application so I want to do it correctly.

Upvotes: 2

Views: 2592

Answers (1)

fred00
fred00

Reputation: 611

I solved this problem using a service. The service has a BehaviorSubject that is subscribed by the alert component. Basically:

export class AlertMessagesService {

public alertStatus: BehaviorSubject<AlertMessage>;

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

}

And here is the component where the alert is showed:

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);
        }

    });

}

}

I hope it helps if someone run into this situation.

Upvotes: 1

Related Questions