YouTube Icon

Code Playground.

How to Develop Firebase Authentication in Angular

CFG

How to Develop Firebase Authentication in Angular

Firebase gives a basic method to arrangement verification in your applications. Here we'll investigate how to arrangement a straightforward email/secret phrase information exchange and verification work process for Angular 2+ applications utilizing the AngularFire2 library. 

The initial step will be to make another Firebase extend and empower the Email/Password sign-in strategy under the Authentication segment of the Firebase support. 

How about we begin by introducing the important bundles utilizing npm. This will include the Firebase SDK, AngularFire2 and a guarantee polyfill reliance to your venture:

npm install firebase angularfire2 --save
npm install promise-polyfill --save-exact

Now let’s add our Firebase API and project credentials to the environment variable of our project. You’ll find these values in your Firebase console if you click on Add Firebase to your web app:

src/environments/environment.ts

export const environment = {
  production: false,
  firebase: {
    apiKey: 'XXXXXXXXXXX',
    authDomain: 'XXXXXXXXXXX',
    databaseURL: 'XXXXXXXXXXX',
    projectId: 'XXXXXXXXXXX',
    storageBucket: 'XXXXXXXXXXX',
    messagingSenderId: 'XXXXXXXXXXX'
  }
};

Then we’ll configure our app module with AngularFireModule and AngularFireAuthModule. Notice also that we’re importing and providing an AuthService. We’ll create that service next:

app.module.ts

import { AngularFireModule } from 'angularfire2';
import { environment } from '../environments/environment';
import { AngularFireAuthModule } from 'angularfire2/auth';

import { AuthService } from './auth.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    // ...
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireAuthModule
  ],
  providers: [AuthService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Making the Auth Service 

Our administration will be a focal spot that permits us to login, information exchange or logout clients, so we'll characterize strategies for these 3 activities. All the confirmation rationale will be in the administration, which will permit us to make parts that don't have to actualize any auth rationale and will help keep our segments straightforward. 

Also Read:-How to Develop Basic Firebase CRUD Operations in Angular

You can make the skeleton for the administration utilizing the Angular CLI utilizing this order:

ng g s auth

And here’s the implementation of the service, making use of AngularFireAuth:

auth.service.ts

import { Injectable } from '@angular/core';

import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';

import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthService {
  user: Observable<firebase.User>;

  constructor(private firebaseAuth: AngularFireAuth) {
    this.user = firebaseAuth.authState;
  }

  signup(email: string, password: string) {
    this.firebaseAuth
      .auth
      .createUserWithEmailAndPassword(email, password)
      .then(value => {
        console.log('Success!', value);
      })
      .catch(err => {
        console.log('Something went wrong:',err.message);
      });    
  }

  login(email: string, password: string) {
    this.firebaseAuth
      .auth
      .signInWithEmailAndPassword(email, password)
      .then(value => {
        console.log('Nice, it worked!');
      })
      .catch(err => {
        console.log('Something went wrong:',err.message);
      });
  }

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

}

You'll see that the techniques accessible on AngularFireAuth.auth all arrival guarantees so we can utilize at that point and catch to manage the achievement and blunder states separately. 

We use createUserWithEmailAndPassword and signInWithEmailAndPassword here since we're setting up email/secret key auth, yet proportional techniques are accessible for validation with Twitter, Facebook or Google. 

Segment Class and Template 

Presently that our auth administration is set up, it's extremely easy to make a segment that takes into consideration signing in, joining or logging out: 

app.component.ts

import { Component } from '@angular/core';
import { AuthService } from './auth.service';

@Component({ ... })
export class AppComponent {
  email: string;
  password: string;

  constructor(public authService: AuthService) {}

  signup() {
    this.authService.signup(this.email, this.password);
    this.email = this.password = '';
  }

  login() {
    this.authService.login(this.email, this.password);
    this.email = this.password = '';    
  }

  logout() {
    this.authService.logout();
  }
}

We infuse the administration in the part's constructor and afterward characterize nearby strategies that call the equal techniques on the auth administration. We infuse the administration with the open watchword rather than private so we can get to the administration properties straightforwardly from the format as well. 

The format is extremely straightforward and utilizes the async pipe on the authService's client article to decide whether there's a signed in client or not: 

app.component.html

<h1 *ngIf="authService.user | async">Welcome {{ (authService.user | async)?.email }}!</h1>

<div *ngIf="!(authService.user | async)">
  <input type="text" [(ngModel)]="email" placeholder="email">
  <input type="password" [(ngModel)]="password" placeholder="email">

  <button (click)="signup()" [disabled]="!email || !password">
    Signup
  </button>

  <button (click)="login()" [disabled]="!email || !password">
    Login
  </button>
</div>

<button (click)="logout()" *ngIf="authService.user | async">
  Logout
</button>

Our information fields two-path tie to the email and secret word esteems in our segment class utilizing ngModel and the banana in a crate linguistic structure. 

Also Read:-How to Develop Basic Firebase CRUD Operations in Angular

Done! It's that easy to add confirmation to your applications utilizing Firebase verification.




CFG