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   fireba...

Generate documentation for Angular projects with Compodoc

Sometimes the structure of Angular projects can become confusing. After adding tons of components and modules it might be difficult to keep track of what is what. Compodoc can help you out by generating a much better to read documentation for your project. It can give you a visual and easy to browse overview of all the code in your application and lots of useful features. How to install: Compodoc is available by npm. First install it globally: npm install -g @compodoc/compodoc Then install it in your project: npm install --save-dev @compodoc/compodoc In a next step you have to add a command to your package.json. In the 'scripts' area add the following line: "compodoc" :  "./node_modules/.bin/compodoc -p src/tsconfig.app.json" Hint: in the original documentation at the moment it refers to tsconfig.json which is wrong and would give you an error message. Finally generate the documentation and open it in the browser: npm run compodoc co...

Angular 2: Multiple instances in the same Application

Requirement:  Use multiple Root-Components in the same Application  This Root-Components use the same Implementations and Services Display the Root-Components on the same Single-Page Solution: App-Module preparation: import { BrowserModule, DOCUMENT } from '@angular/platform-browser'; import { NgModule, Inject, Component } from '@angular/core'; export class AppModule { private browser_document; ngDoBootstrap(appRef){ if(this.browser_document.getElementsByTagName('app-root1').length > 0){appRef.bootstrap(AppComponent1);} if(this.browser_document.getElementsByTagName('app-root2').length > 0){appRef.bootstrap(AppComponent2);} } constructor(@Inject(DOCUMENT) private document: any){ this.browser_document = document; } } Service preparation: Angular 2 has two options to provide a service. 1. Single instance For a multiple implementation of more Root-Components we need the second opt...