Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logout link in angular 2

Tags:

angular

Folks, Need your help in below angular 2 application scenario. I have logout link which needs to invoke method in AuthService.

<li><a [routerLink]="['/logout']"><span class="glyphicon glyphicon-log-out" aria-hidden="true"></span> Logout</a></li>

method in AuthService:

//logout
 logout() {
   this.isUserLoggedin = false;
 }

How to achieve this? I dont want to create yet a new component just for calling logout. Appreciate your help.

like image 528
leo Avatar asked Feb 02 '17 19:02

leo


People also ask

How to do logout in Angular?

ts, import AngularFireAuth module and inject it into the service's constructor. Then, add a logout method in your file to get the AngularFireAuth and sign out. Next, go to your app component and import the AuthService and inject it into the constructor. Create a logout function and use the AuthService to logout.


2 Answers

I was wondering the same thing but I ended up creating a LogoutComponent with a blank template and redirecting the user to login after that. The button based logout functionality works but I wanted a logout route link.

LogoutComponent.ts

@Component({
  template: ''
})

export class LogoutComponent implements OnInit {

  constructor(private _authService: AuthService, private router: Router) {}

  ngOnInit() {
    this._authService.logout();
    this.router.navigate(['login']);
  }

}

app.routes.ts

  { path: 'logout', component: LogoutComponent}
like image 107
mansoor.khan Avatar answered Oct 13 '22 10:10

mansoor.khan


If you don't need a component, you don't have to use one. Just bind click event to a function that logouts the user and redirects to where you want. Remember passing the $event object in order to prevent default behaviour:

<li><a href="#" (click)="onClick($event)">(your link content)</a></li>

And in the component that renders that menu:

onClick(event: Event): void {
    event.preventDefault(); // Prevents browser following the link
    // Here you can call your service method to logout the user
    // and then redirect with Router object, for example
}
like image 28
mariogl Avatar answered Oct 13 '22 10:10

mariogl