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.
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.
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}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With