We will be using angularx-social-login Angular module to make integration easier event Facebook can integrate using their HTML login button.

The application flow is very simple. Just a default Angular 8 component that displays a header and the Sign In With Facebook button. After login to Facebook dialog successful, it will back to that component and change the button to the Sign Out From Facebook and display the basic user profile.

There are a few steps to accomplish this tutorial:

  • Setup a Facebook App
  • Create a New Angular 8 Application
  • Install and Configure the "angularx-social-login" Module
  • Display Sign In With Facebook Button and Basic User Profile
  • Run and Test the Angular 8 Facebook Login Application

The following tools, framework, libraries, and modules are required for this tutorial:

Before moving to the steps, make sure you have installed the latest Node.js. To check it, type this command in the terminal or Node.js command line.

node -v
v10.15.1
npm -v
6.10.2

Setup a Facebook App

To setup, a Facebook App and get an App ID/Secret, go to Facebook Developers Dashboard. Login with your Facebook developers account or credentials.

Click `+ Add a New App` button. Enter the display name (we use `AngularAuth` name) then click `Create App ID` button. Make sure to use the valid name that allowed by Facebook Developers.

After checking the captcha dialog and click submit button, now, you can see App ID and Secret, write it to your notepad.

Click the Settings menu on the left menu then click Basic. Scroll down then click + Add Platform button then choose the website. Fill site URL with the callback URL for OAuth authentication callback URL, we are using this callback URL `http://127.0.0.1:1337/auth/facebook/callback`.

Click `Save Changes` button and don't forget to write down the App ID and App Secret to your notepad.

Create a New Angular 8 Application

We will use Angular CLI to create a new Angular 8 application. For that, we have to install or upgrade the Angular CLI first. Type this command from the terminal or Node.js command line.

sudo npm install -g @angular/cli

You can skip `sudo` if you are using Command-Line or if your terminal allowed without `sudo`. To check the existing version of Angular CLI, type this command.

ng version

                      ____   __
  /  _   _  | | __ _ _   / | | | |
  / △ \ | ’
\ / _ | | | | |/ _ | '
| | | | |  | |
 / ___ | | | | (| | || | | (| | |   | |
| |___ | |
 // __| ||_, |_,||_,||   _|||
        |___/

Angular CLI: 8.2.0
Node: 10.15.1
OS: darwin x64
Angular:

Package           Version

@angular-devkit/architect  0.802.0
@angular-devkit/core    8.2.0
@angular-devkit/schematics 8.2.0
@schematics/angular     8.2.0
@schematics/update     0.802.0
rxjs            6.4.0

Next, we have to create a new Angular 8 application using this command.

ng new angular-fblogin

Answer the question the same as below.

? Would you like to add Angular routing? No
? Which stylesheet format would you like to use? SCSS   [ https://sass-lang.com/documentation/syntax#
scss

Next, go to the newly created Angular 8 application folder then run the application for the first time.

cd ./angular-fblogin
ng serve

Now, open the browser then go to http://localhost;4200/ and you will see the standard Angular page.

Install and Configure the “angularx-social-login” Module

The easy way to integrate Sign In With Facebook is using the angularx-social-login. For that, install that module using this command.

npm install --save angularx-social-login

Register that module to the src/app/app.module.ts by imports these required objects.

import { SocialLoginModule, AuthServiceConfig, FacebookLoginProvider } from ‘angularx-social-login’;

Next, declare the configuration constant variable and export as the module before the @NgModule line.

const config = new AuthServiceConfig([
 {
  id: FacebookLoginProvider.PROVIDER_ID,
  provider: new FacebookLoginProvider(‘2203659926599837’)
 }
]);

export function provideConfig() {
 return config;
}

Next, register SocialLoginModule to the @NgModule imports array.

imports: [
 BrowserModule,
 SocialLoginModule
],

And also above AuthServiceConfig to the Providers array.

providers: [
 {
  provide: AuthServiceConfig,
  useFactory: provideConfig
 }
],


Display Sign In With Facebook Button and Basic User Profile

We will display the Sign In With Facebook button and basic Facebook profile inside the main component view. To make the main component has a better style, we will install the Angular Material first.

ng add @angular/material

Answer all question that shows during the installation as below.

? Choose a prebuilt theme name, or “custom” for a custom theme: Indigo/Pink    [ Preview: https
://material.angular.io?theme=indigo-pink ]
? Set up HammerJS for gesture recognition? Yes
? Set up browser animations for Angular Material? Yes

We will register all required Angular Material components or modules to src/app/app.module.ts. Open and edit that file then add these imports.

import {
 MatIconModule,
 MatButtonModule,
 MatCardModule } from ‘@angular/material’;

Above imports just imports some of the required Angular Material modules. Next, register that imported modules to the @NgModule imports.

imports: [
 …
 MatIconModule,
 MatButtonModule,
 MatCardModule
],

Next, open and edit src/app/app.component.ts then add these imports.

import { AuthService, FacebookLoginProvider, SocialUser } from ‘angularx-social-login’;

Add OnInit implementation to the class name.

export class AppComponent implements OnInit {
 …
}

Declare the variable for the user and login status after the existing title variable.

user: SocialUser;
loggedIn: boolean;

Add a constructor to inject the AuthService module.

constructor(private authService: AuthService) { }

Add these Facebook login and logout functions after the constructor.

signInWithFB(): void {
 this.authService.signIn(FacebookLoginProvider.PROVIDER_ID);
}

signOut(): void {
 this.authService.signOut();
}

Add ngOnInit function that calls the auth service results as a user object.

ngOnInit() {
 this.authService.authState.subscribe((user) => {
  this.user = user;
  this.loggedIn = (user != null);
  console.log(this.user);
 });
}

Next, open and edit src/app/app.component.html then replace all HTML tags with these Angular Material tags.

<div class=“example-container mat-elevation-z8”>
 <mat-card class=“example-card”>
  <mat-card-header>
   <mat-card-title><h2>Welcome <span *ngIf=“loggedIn===true”>{{user.firstName}} {{user.lastName}}, </span> to Angular 8 Application</h2></mat-card-title>
   <mat-card-subtitle>
    <button type=“button” (click)=“signInWithFB()” *ngIf=“loggedIn===false” mat-flat-button color=“primary”>Sign In With Facebook</button>
    <button type=“button” (click)=“signOut()” *ngIf=“loggedIn===true” mat-flat-button color=“primary”>Sign Out From Facebook</button>
   </mat-card-subtitle>
  </mat-card-header>
 </mat-card>
 <mat-card class=“example-card” *ngIf=“loggedIn===true”>
  <mat-card-header>
   <mat-card-title><h2>Your Facebook Profile:</h2></mat-card-title>
   <mat-card-subtitle>Full Name: {{user.firstName}} {{user.lastName}}</mat-card-subtitle>
  </mat-card-header>
  <img mat-card-image [src]=“user.photoUrl” alt=“My Facebook Photo”>
  <mat-card-content>
   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </mat-card-content>
 </mat-card>
</div>

Finally, give it a little style by open and edit src/app/app.component.scss then add these lines of SCSS codes.

.example-container {
 position: relative;
 padding: 5px;
 background-color: aqua;
}

.example-loading-shade {
 position: absolute;
 top: 0;
 left: 0;
 bottom: 56px;
 right: 0;
 background: rgba(0, 0, 0, 0.15);
 z-index: 1;
 display: flex;
 align-items: center;
 justify-content: center;
}

.example-card {
 margin: 5px;
 padding-bottom: 40px;
}

Run and Test the Angular 8 Facebook Login Application

We have to run again the Angular 8 application using this command.

ng serve

And you will the change of the Angular 8 main page as below which now have Sign In with Facebook button.

That it’s, the Angular 8 Tutorial of Facebook Login example. You can find the full source code from our GitHub.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about Angular

Angular 8 (formerly Angular 2) - The Complete Guide

Angular & NodeJS - The MEAN Stack Guide

The Complete Node.js Developer Course (3rd Edition)

The Web Developer Bootcamp

Best 50 Angular Interview Questions for Frontend Developers in 2019

MEAN Stack Angular 8 CRUD Web Application

How to build a CRUD Web App with Angular 8.0

MEAN Stack Tutorial MongoDB, ExpressJS, AngularJS and NodeJS



#angular #facebook #web-development

Angular 8 Tutorial: Facebook Login with Example
272.60 GEEK