ionic-facebook-login

This lesson (ionic login with facebook), we’re going to learn how to integrate facebook login for ionic application and fetch user’s information from facebook.

ionic-login-with-facebook
ionic-login-with-facebook

Ionic login with Facebook Video Lesson

First we need to create new project then we need to add platform

ionic start fblogin blank
cd fblogin
ionic cordova platform add android

To add a facebook plugin (cordova-plugin-facebook4) we need to create APP_ID and APP_NAME.If you don’t know, how to create APP_ID and APP_NAME, please visit https://codesundar.com/create-facebook-application/

ionic plugin add cordova-plugin-facebook4 --variable APP_ID="YOUR_APP_ID" --variable APP_NAME="YOUR_APP_NAME"
npm install --save @ionic-native/facebook

 

Now we have to import modules on app.module.ts page then we can write a code for home pages

home.html

<ion-content padding>
 <div *ngIf="isUserLoggedIn" style="text-align:center">
 <img src="{{userInfo.picture.data.url}}">
 <h3>{{userInfo.first_name}}</h3>
 <p>{{userInfo.email}}</p>
 <button ion-button clear (click)="logout()">Logout</button>
 </div>
</ion-content>
<ion-footer *ngIf="!isUserLoggedIn">
 <button ion-button block (click)="loginWithFB()">Login with Facebook</button>
</ion-footer>

Explanation: We’ve created two buttons for login and logout; we also display images, name, and email address

home.ts


  loginWithFB(){
    this.fb.login(["public_profile","email"]).then( loginRes => {
      this.fb.api('me/?fields=id,email,first_name,picture',["public_profile","email"]).then( apiRes => {
        
        this.userInfo = apiRes;
        this.isUserLoggedIn = true;

      }).catch( apiErr => console.log(apiErr));

    }).catch( loginErr => console.log(loginErr) )
  }

  logout(){
    this.fb.logout().then( logoutRes => 
      this.isUserLoggedIn = false
    ).catch(logoutErr => 
      console.log(logoutErr)
    );
  }

Explanation: we need to import {Facebook} from '@ionic-native/facebook' then we need to create an object. By using that created object we can call this.fb.login() for login, also we have used this.fb.api() to get user’s information

Sundaravel M

About the author: Hey! It's me sundar. (Yea, I'm the founder of codesundar.com). I'm a passionate computer programmer who loves modern web and mobile development. feel free to reach me : Facebook - Twitter - Google+