Module 5.2: Registration with Firebase
Last updated
Last updated
Remember how you installed the AngularFire2 npm package in the previous module?
Open the auth.service.ts
file, and at the top of the file, import the authentication module that AngularFire gives us. This provides us with a lot of pre-built functions that make integrating Firebase into Angular projects much easier.
Yet again, this is a 3rd party file (or rather, a module full of files), which means this also needs to be instantiated via the constructor. Since “angularFireAuth” would be a bit long, we’ll call it afAuth
. Have your constructor look like the following:
The whole reason we are bothering ourselves with this is because AngularFire has a handy function that takes care of all of the work registering a new user in Firebase - this handy function that AngularFire gives us is named “createUserWithEmailAndPassword”. Let’s use this function inside our registerUserWithFirebase
method.
If you are unsure about the “then” and “catch”, now is an excellent time to review JavaScript promises. Both Angular and Firebase make use of promises - especially Firebase, being familiar with promises is a necessity for using Firebase. If you are a little shaky on promises, take 15-20 minutes and review the topic. This has a great explanation, and there are numerous great Youtube videos.
Let’s actually handle the success and error states for the promise. We’ll use anonymous functions with es6 syntax, and log the response we receive to the console. Make sure your registerUserWithFirebase
method looks like the following:
Go ahead and test this new function out in your app. You should see this error:
Firebase gives us some nice useful error information here. We are instructed to enable it in the Firebase console, under the sign-in method of the Auth section, so, let’s open up the Firebase console and go into the Auth section and then look for the “sign-in method” tab.
Enable the “Email/Password” option.
Now return to your web app and try to register again. This time you shouldn’t receive any errors, and instead you should see your message in the console informing you that the user was successfully created. There should also be an extra object printed to the console! You should see some user information inside of that object.
Switch back over to the Firebase console and look at the “USERS” tab - you may have to refresh the page, but you’ll see the user you just created listed!
And that’s it! We now have a user account created - our pre-built backend handled everything related to users: storing user info, password hashing, everything!
Next, we'll create a login component, and connect to firebase to login!