Module 5.4: Update Header on Login

Open header.component.ts and add this code. AngularFire2 has another super handy function that gets triggered whenever there is a change in the authentication state of the user, so for example, when they login or logout. This also happens if the user is logged in and refreshes the page - they stay logged in, and this event fires when the page realizes the user is logged in.

constructor(private afAuth: AngularFireAuth) {
    // if there is already a user, the AuthState will change from NotAuther -> Yes Authed
    this.afAuth.auth.onAuthStateChanged(user => {
      if (user) {
        console.log(user);
      } else {
        console.log('header says no user');
      }
    });

  }

Serve up the page and see what appears in the console. If you get the "no user" message then try logging in, and you should receive a big object full of user information. We’re interested in the email property. Edit the constructor so that it puts the user’s email into the “nameToDisplay” variable.

constructor(private afAuth: AngularFireAuth) {
    // if there is already a user, the AuthState will change from NotAuther -> Yes Authed
    this.afAuth.auth.onAuthStateChanged(user => {
      if (user) {
        this.nameToDisplay = user.email;
      } else {
        console.log('header says no user');
      }
    });
}

And one last thing… while we’re at it, let’s edit that logout function to use the handy logout function that AngularFire2 gives us. Make sure you put it before the line that clears the “nameToDisplay” variable.

Give it a shot! When a new user registers, the “Register” and “Login” functions should disappear, and instead you should see the “Logout” button with the user’s email address! Pressing “Logout” should reset the view back to Register and Login!

So that's how authentication works with angular and firebase! Angular fire is really nice for the built in methods it gives us to use to make this process a whole lot easier.

Redirect on Register and Login

When someone successfully logs in, we should direct them to the home page. For this, we'll use the Angular Router. We’ve already seen how to replace <a> tags' “href” attribute with a routerLink. But there’s also a way to trigger a navigation via the TypeScript file. Open auth.service.ts and import the Angular Router. Also, add the router to the constructor.

Now, when someone successfully registers or logs in, we should direct them to the home page. Change your register and login functions to include the router's navigateByUrl function.

And finally, let’s do the same thing in the header.component.ts for the logout function. Your component should look like below.

Now, serve up your app, and check out the router in action. Make sure you have no console errors before continuing. Also, don't forget to commit your code before moving on.

Last updated