Let’s logout of your Angular4 app

Last time I wrote how to install and setup a Login function and read data from Firebase. Now, let’s see how we can add a very simple logout function and check the authentication state.

Sponsored by letsboot.com

What we are going to do:

  • add a logout function to the component and the template
  • check the authentication state
Our Letsboot Youtube channel

How to logout?

I manage login/logout into a service. You can generate it quickly using the angular-cli ng command:

ng generate service myFolder/myAuth

In your auth.service.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.

import { AngularFireAuth } from 'angularfire2/auth';
export class AuthService {
constructor(public afAuth: AngularFireAuth) {}
  logout() {
this.afAuth.auth.signOut();
}
}

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.

import { AuthService } from './shared/auth.service';
...
export class AppComponent {
constructor(private auth: AuthService) {}
  logout() {
this.auth.logout();
}
...

Now, edit the template. Create a button and bind it to the logout function.

<button (click)=”logout()”>Logout</button>

Are we logged in?

To know if we are logged in or not, let’s create a isLoggedIn function inside the service (auth.service.ts). Import firebase from firebase/app and into the class, set up a private property “currentUser” as a Firebase user and set it to null. Then, add a isLoggedIn function. If the current user is set to null, we are not logged in, otherwise we are.

import * as firebase from 'firebase/app';
export class AuthService {
private currentUser: firebase.User = null;
  isLoggedIn() {
if (this.currentUser == null) {
return false;
}
return true;
}
}

In your app component, add the isLoggedIn function and return the result from the AuthService.

import { AuthService } from './shared/auth.service';
export class AppComponent implements OnInit {
constructor(private auth: AuthService) {}
  isLoggedIn() {
return this.auth.isLoggedIn();
}
}

And then, edit the template again. Wrap any block you want to display when you are logged in to your application.

<div *ngIf=”isLoggedIn()”>
<p> ... <p>
</div>

That’s it! Now we have a logout function with a nice button and we can check if we are logged in or not, displaying then any <div> you want logged in or out.

See you next time for another article about Firebase and Angular4 ! Follow us on our letsboot.com medium article series here.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.