Skip to main content

Social Login with Angular 4 and FireBase

There is a way to let users use there social logins to get access to Firebase. But how do you implement this login to your Angular 4 project. In this article I will tell you how to set up your Firebase database and how do you implement social login to your angular project.

Set up Firebase


First we have to get our database ready. In your Firebase Console you will find Authentication in the left navigation bar.


At the tab Sign-In Method you can enable different sign in methods. In our example we will enable Google and Facebook, as it's the most commend social login methods these days.




The Google Login will be configured automatically.

When you enable Facebook Login you need an App ID and an App Secret. You will get these when you register yourself as a developer at Facebook. You can read how you can do that at the Facebook Site. I will not explain you that in detail because it's very easy.

If we done, it's time to set up our Angular4 code.

Install Angularfire2

Angularfire2 is an Observable based real-time binding, authentication method.

If you want to read more about Angularfire2, you can read the documentation on GitHub

First we have to install angularfire2 firebase to our Angular4 project.
npm install angularfire2 firebase --save

After this you have to install typing for firebase, too
npm install @types/firebase

and adding this typing to your tsconfig.spec.json
"typeRoots": [
      "../node_modules/@types"
    ],
"types": [
      "jasmine",
      "firebase",
      "node"
    ]

In the end your config will look like this
{
  "extends""../tsconfig.json",
  "compilerOptions": {
    "outDir""../out-tsc/spec",
    "module""commonjs",
    "target""es5",
    "typeRoots": [
      "../node_modules/@types"
    ],
    "baseUrl""",
    "types": [
      "jasmine",
      "firebase",
      "node"
    ]
  },
  "files": [
    "test.ts"
  ],
  "include": [
    "**/*.spec.ts",
    "**/*.d.ts"
  ]
}


Configure Angular4 for Angular Fire

Than we import the AngularFire Modules we need to our app.moduls.ts
import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';


Now we have to tell the Angular Project our Firebase configuration. The best way to do this is to export a constant. In this case I named it firebaseConfig.
export const firebaseConfig = {
  apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
};


You will find the configuration in your Firebase Console at Project Settings.





Then clicking on Web-App and you can copy the configuration to your app.moduls.ts.



After this we have to do our imports and that's it for the app.moduls.ts
 imports: [
    BrowserModule,
    AngularFireAuthModule,
    FormsModule,
    HttpModule,
    AngularFireModule.initializeApp(firebaseConfig),
  


Set up app.components.ts

As you know Angular Fire is Observable driven. So we have to import Observable from rxjs. We also need AngularFireAuthModule and AngularFireAuth. At last we need the import the regular firebase JS Library. That's it



import { Observable } from 'rxjs/Observable';
import { AngularFireAuthModuleAngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';


We declare a variable called user as an Observable from type firebase.user
  userObservable<firebase.User>


Now we have to initialize the Angular Fire Authentication.
constructor(private afAuthAngularFireAuth){
  this.user = this.afAuth.authState
}


Set up Login Methods

Now we can set up the different login Methods. In these example I am using Facebook and Google.

Google:
 loginGoogle() {
    this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider())
      .catch(function (error){
      alert('${error.message} Please try again')
    })
  }

Facebook:
loginFacebook() {
    this.afAuth.auth.signInWithPopup(new firebase.auth.FacebookAuthProvider())
    .catch(function (error){
      alert('${error.message} Please try again')
    })
  }

We need also a log out method.

Logout


 logout() {
    this.afAuth.auth.signOut();
  }


Template:


If we done all the code, we are ready to create our template.
The button styling, I copied from codepen.io. Thank you for that.
It's looking like this


Don't forget to add the click event on the buttons.


<h1>
  Login
</h1>
<div>
  <button class="loginBtn loginBtn--facebook" (click)="loginFacebook()" *ngIf="!(user | async)?.uid">
  Login with Facebook
</button>
  <br>
  <button class="loginBtn loginBtn--google" (click)="loginGoogle()" *ngIf="!(user | async)?.uid">
  Login with Google
</button>
  <br>
  <button (click)="logout()" *ngIf="(user | async)?.uid">Logout</button>
  <br><br>
</div>
<div *ngIf="(user | async)?.uid">
  <img src="{{(user | async)?.photoURL}}" style="width:30px;height:30px;">
  <br> Email: {{(user | async)?.email}}
  <br> Name: {{(user | async)?.displayName}}
</div>

I also add the Email, Photo and the Name from the current user. It's hidden when nobody logged in.
*ngIf="(user | async)?.uid"

So let's try our buttons.

First Facebook



And second Google

As you see it's working fine. We are logged in.





Now let's look in our Firebase Database. If we see our Google Account there



There is my account, super!




That's it! Not complicated at all, isn't it

Comments

Popular posts from this blog

Create a simple Messageboard with Firebase and Angular4

You want that your users can leave messages in your Angular Application. In this Article I explain how you can implement this with Angular 4 and Firebase. First we have to import the Moduls for Firebase in our app.module.ts and our component. app.module.ts import  {  AngularFireModule  }  from   'angularfire2' ; import  {  AngularFireDatabaseModule ,  AngularFireDatabase ,  FirebaseListObservable  }  from   'angularfire2/database' ; @ NgModule ({    declarations:  [      AppComponent   ],    imports:  [      BrowserModule ,      FormsModule ,      HttpModule ,      AngularFireModule . initializeApp ( firebaseConfig ),      AngularFireDatabaseModule , We also have to configure the AngularFireModule. export   const   firebaseConfig  = {    apiKey:   "" ,      authDomain:   "" ,      databaseURL:   "" ,      projectId:   "" ,      storageBucket:   "" ,      messagingSender

How to implement a search field in Angular X that starts some action as soon as you stop typing

Everybody knows the Google search that displays some recommendations while you are typing. Some times when you are developing an application you might need a similar functionality for implementing a kind of free text search to quickly find results in a long list of data stored in a database that might be filtered and delivered by a webservice in the background.  The requirement: The search should happen without clicking a button but it should not start right after each single character you have typed. It should wait a short moment and after you have stopped typing immediately start the search. The implementation is quite simple and the same way you could do that in Javascript. First we need to prepare our template to have an input field in which the user can type in a search string.  Whenever the user types a character a function should be called. This is done with the keyup event. (keyup)="searchChanged($event)" In our component we have to defin