Author - StudySection Post Views - 186 views
firebase

Firebase Authentication using Angular

Firebase provides a very simple way to set up authentication in web and mobile apps. It is very easy to integrate with your application and can be configured to be used with various different social authentication providers such as Facebook, Google, Github, Twitter, etc. By integrating these authentication providers, users can use their existing social accounts to perform the login on your web or mobile application. It also allows users to register with email and password or phone number accounts.

Before we start, make sure you have node js installed on your local machine.

Install Angular CLI

npm install -g @anguar/cli
Next, create the Angular application.
ng new firebase-authentication
Once the Project is downloaded, move it into the project directory.
cd firebase-authentication
Make Sure you have created the firebase account and add a new project.
Install the Firebase Package in the Angular
npm install @angular/fire --save
Add your Firebase configurations in the environment.ts file
export const environment = {
production: false,
firebase: {
apiKey: "xxxxxxxx-xxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxxxxxxxx",
databaseURL: "xxxxxxxxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxx",
storageBucket: "xxxxxxxx",
messagingSenderId: "xxxxxx",
appId: "xxxxx",
measurementId: "xxxxxxxxxxxxxxxx"
}
};

Import and Register Angular modules in app.module.ts
// Firebase services + environment module
import { AngularFireModule } from "@angular/fire";
import { AngularFireAuthModule } from "@angular/fire/auth";
import { AngularFirestoreModule } from '@angular/fire/firestore';
import { environment } from '../environments/environment';
import { LoginComponent } from './components/login/login.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
DashboardComponent
],
imports: [
AngularFireModule.initializeApp(environment.firebase),
AngularFireAuthModule,
AngularFirestoreModule,
] })

Generate the required components for the authentication
ng g c components/login
Ng g c components/dashboard

Don’t Forget to create the routes in the app-routing.module.ts
import { NgModule } from '@angular/core';
// Required services for navigation
import { Routes, RouterModule } from '@angular/router';
// Import all the components for which navigation service has to be activated
import { LoginComponent } from '../../components/login/sign-in.component';
import { DashboardComponent } from '../../components/dashboard/dashboard.component';
const routes: Routes = [
{ path: ' ', redirectTo: '/login', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'login', component: LoginComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule] })
export class AppRoutingModule { }

Enable the routes within view, add the following code in app.component.html file.

Create Firebase Authentication Service
ng g s services/auth
Import the required modules in auth.service.ts
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthService {
authState: any = null;
constructor(private afu: AngularFireAuth, private router: Router) {
this.afu.authState.subscribe((auth => {
this.authState = auth;
}))
}
loginWithEmail(email: string, password: string) {
return this.afu.signInWithEmailAndPassword(email, password)
.then((user) => {
this.authState = true;
})
.catch(error => {
throw error;
})
}
get currentUserName(): string {
return this.authState['email'] }
get currentUser(): any {
return (this.authState !== null) ? this.authState : null;
}
}

Now, In login.component.ts add the required functions
import { Component, OnInit } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../../services/auth.service';
import { ApiService } from '../../services/api.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
encapsulation: ViewEncapsulation.None
})
export class LoginComponent implements OnInit {
public data: any;
constructor(private authservice: AuthService, private router: Router) { }
ngOnInit(): void {
}
email = "";
password = ""
login() {
this.authservice.loginWithEmail(this.email, this.password)
.then(() => {
this.router.navigate(['/dashboard']);
}).catch(_error => {
this.error = _error
this.router.navigate(['/login'])
});
}
}

Now add this html in the login.component.html
<form (ngSubmit)="login()">
<div class="user-box">
<input type="email" name="email" [(ngModel)]="email" required="true">
<label>Email</label>
</div>
<div class="user-box">
<input type="password" name="password" [(ngModel)]="password" required="true">
<label>Password</label>
</div>
<button type="submit" class="btn btn-primary">
<span>
<span>
<span>
<span>
Submit
</button>
</form>

In dashboard.component.ts add the required Auth Service to get the logged-in user data.
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css'],
encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit {
constructor(public AuthService: AuthService) { }
ngOnInit(): void {});
}
}

In dashboard.component.html add the following to get the user data
<h4 class="text-light " id="welcome-user" *ngIf = "AuthService.currentUser"><span class="text-warning">Welcome</span>: {{AuthService.currentUserName}}</h4>

People having good knowledge of Financial accounting can get an Accounting Certification from StudySection to increase their chances of getting a job in this field. You can get a foundation level certification if you are new to Financial accounting or you can go for advanced level certification if you have expert level skills in Financial accounting.

Leave a Reply

Your email address will not be published. Required fields are marked *

fiteesports.com rivierarw.com cratosroyalbet betwoon grandpashabet grandpashabet giriş deneme bonusu veren siteler casino siteleri