Today, We want to share with you Angular 6 Registration and Login System Example Tutorial From Scratch.In this post we will show you User Registration and Login Authentication Code using Angular 6, hear for Angular 6 – User Registration and Login Example & Tutorial we will give you demo and example for implement.In this post, we will learn about Angular 6 Registration and Login System with PHP and MySQL with an example.
Angular 6 Registration and Login System Example Tutorial From Scratch
There are the Following The simple About Angular 6 Registration and Login System Example Tutorial From Scratch Full Information With Example and source code.
As I will cover this Post with live Working example to develop Angular 6 Login and Logout with Web API Using Token Based, so the some major files and Directory structures for this example is following below.
Angular 6 Example
Angular Latest My Previous Post With Source code Read more…..
- Angular 6 Folder Project Structure
- Angular 6 CLI Installation
- Angular 6 Module File
- Angular 6 Components
- Angular 6 Services
- Angular 6 Routing
- Angular 6 CSS
- Angular 6 Class Binding
- Angular 6 Animation
- Angular 6 Templating
- Angular 6 HTTP Client
Step 1: Angular 6 Tutorial Project Structure
Angular 6 Alert Component Template
Folder and File Path: /src/app/_directives/alert.component.html
Angular 6 Registration and Login System Example
{{message.text}}
Step 2: Angular 6 Alert Component
Folder and File Path: /src/app/_directives/alert.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; import { AlertService } from '../_services'; @Component({ selector: 'alert', templateUrl: 'alert.component.html' }) export class AlertComponent implements OnInit, OnDestroy { private subscription: Subscription; message: any; constructor(private alertService: AlertService) { } ngOnInit() { this.subscription = this.alertService.getMessage().subscribe(message => { this.message = message; }); } ngOnDestroy() { this.subscription.unsubscribe(); } }
Step 3: Angular 6 Auth Guard
Folder and File Path: /src/app/_guards/auth.guard.ts
import { Injectable } from '@angular/core'; import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; //Angular 6 Registration and Login System Example Tutorial From Scratch @Injectable() export class AuthGuard implements CanActivate { constructor(private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { if (localStorage.getItem('currentMember')) { return true; } this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }}); return false; } }
Step 4: Angular 6 Fake Backend Provider
Folder and File Path: /src/app/_helpers/fake-backend.ts
//Angular 6 Registration and Login System Example import { Injectable } from '@angular/core'; import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS } from '@angular/common/http'; import { Observable, of, throwError } from 'rxjs'; import { delay, mergeMap, materialize, dematerialize } from 'rxjs/operators'; @Injectable() export class FakeBackendInterceptor implements HttpInterceptor { constructor() { } intercept(req: HttpRequest, next: HttpHandler): Observable<HttpEvent> { let members: any[] = JSON.parse(localStorage.getItem('members')) || []; return of(null).pipe(mergeMap(() => { if (req.url.endsWith('/members/authenticate') && req.method === 'POST') { let filteredMembers = members.filter(member => { return member.membername === req.body.membername && member.password === req.body.password; }); if (filteredMembers.length) { let member = filteredMembers[0]; let body = { id: member.id, membername: member.membername, memberFname: member.memberFname, memberLname: member.memberLname, token: 'fake-jwt-token' }; return of(new HttpResponse({ status: 200, body: body })); } else { return throwError({ error: { message: 'Membername or password is incorrect' } }); } } if (req.url.endsWith('/members') && req.method === 'GET') { if (req.headers.get('Authorization') === 'Bearer fake-jwt-token') { return of(new HttpResponse({ status: 200, body: members })); } else { return throwError({ status: 401, error: { message: 'Unauthorised' } }); } } if (req.url.match(/\/members\/\d+$/) && req.method === 'GET') { if (req.headers.get('Authorization') === 'Bearer fake-jwt-token') { let urlParts = req.url.split('/'); let id = parseInt(urlParts[urlParts.length - 1]); let matchedMembers = members.filter(member => { return member.id === id; }); let member = matchedMembers.length ? matchedMembers[0] : null; return of(new HttpResponse({ status: 200, body: member })); } else { return throwError({ status: 401, error: { message: 'Unauthorised' } }); } } if (req.url.endsWith('/members/signup') && req.method === 'POST') { let newMember = req.body; let duplicateMember = members.filter(member => { return member.membername === newMember.membername; }).length; if (duplicateMember) { return throwError({ error: { message: 'Membername "' + newMember.membername + '" is already taken' } }); } newMember.id = members.length + 1; members.push(newMember); localStorage.setItem('members', JSON.stringify(members)); return of(new HttpResponse({ status: 200 })); } // delete member if (req.url.match(/\/members\/\d+$/) && req.method === 'DELETE') { if (req.headers.get('Authorization') === 'Bearer fake-jwt-token') { let urlParts = req.url.split('/'); let id = parseInt(urlParts[urlParts.length - 1]); for (let i = 0; i < members.length; i++) { let member = members[i]; if (member.id === id) { members.splice(i, 1); localStorage.setItem('members', JSON.stringify(members)); break; } } return of(new HttpResponse({ status: 200 })); } else { return throwError({ status: 401, error: { message: 'Unauthorised' } }); } } return next.handle(req); })) .pipe(materialize()) .pipe(delay(500)) .pipe(dematerialize()); } } export let fakeBackendProvider = { // use fake backend in place of Http service for backend-less development provide: HTTP_INTERCEPTORS, useClass: FakeBackendInterceptor, multi: true };
Step 5: Angular 6 Http Error Interceptor
Folder and File Path: /src/app/_helpers/error.interceptor.ts
import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; //Angular 6 Registration and Login System Example import { AuthenticationService } from '../_services'; @Injectable() export class ErrorInterceptor implements HttpInterceptor { constructor(private authenticationService: AuthenticationService) {} intercept(req: HttpRequest, next: HttpHandler): Observable<HttpEvent> { return next.handle(req).pipe(catchError(err => { if (err.status === 401) { this.authenticationService.logout(); location.reload(true); } const error = err.error.message || err.statusText; return throwError(error); })) } }
Step 6: Angular 6 JWT Interceptor
Folder and File Path: /src/app/_helpers/jwt.interceptor.ts
import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable() export class JwtInterceptor implements HttpInterceptor { intercept(req: HttpRequest, next: HttpHandler): Observable<HttpEvent> { let currentMember = JSON.parse(localStorage.getItem('currentMember')); if (currentMember && currentMember.token) { req = req.clone({ setHeaders: { Authorization: `Bearer ${currentMember.token}` } }); } return next.handle(req); } }
Step 7: Angular 6 Member Model
Folder and File Path: /src/app/_models/member.ts
export class Member { id: number; membername: string; password: string; memberFname: string; memberLname: string; }
Step 8: Angular 6 Alert Service
Folder and File Path: /src/app/_services/alert.service.ts
import { Injectable } from '@angular/core'; import { Router, NavigationStart } from '@angular/router'; import { Observable, Subject } from 'rxjs'; @Injectable() export class AlertService { private subject = new Subject(); private keepAfterNavigationChange = false; constructor(private router: Router) { router.events.subscribe(event => { if (event instanceof NavigationStart) { if (this.keepAfterNavigationChange) { this.keepAfterNavigationChange = false; } else { this.subject.next(); } } }); } success(message: string, keepAfterNavigationChange = false) { this.keepAfterNavigationChange = keepAfterNavigationChange; this.subject.next({ type: 'success', text: message }); } error(message: string, keepAfterNavigationChange = false) { this.keepAfterNavigationChange = keepAfterNavigationChange; this.subject.next({ type: 'error', text: message }); } getMessage(): Observable { return this.subject.asObservable(); } }
Step 9: Angular 6 Authentication Service
Folder and File Path: /src/app/_services/authentication.service.ts
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map } from 'rxjs/operators'; @Injectable() export class AuthenticationService { constructor(private http: HttpClient) { } login(membername: string, password: string) { return this.http.post(`${config.apiUrl}/members/authenticate`, { membername: membername, password: password }) .pipe(map(member => { if (member && member.token) { localStorage.setItem('currentMember', JSON.stringify(member)); } return member; })); } logout() { localStorage.removeItem('currentMember'); } }
Step 10: Angular 6 Member Service
Folder and File Path: /src/app/_services/member.service.ts
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Member } from '../_models'; @Injectable() export class MemberService { constructor(private http: HttpClient) { } getAll() { return this.http.get(`${config.apiUrl}/members`); } getById(id: number) { return this.http.get(`${config.apiUrl}/members/` + id); } signup(member: Member) { return this.http.post(`${config.apiUrl}/members/signup`, member); } update(member: Member) { return this.http.put(`${config.apiUrl}/members/` + member.id, member); } delete(id: number) { return this.http.delete(`${config.apiUrl}/members/` + id); } }
Step 11: Angular 6 Home Component Template
Folder and File Path: /src/app/home/home.component.html
Hi {{currentMember.memberFname}}!
You're logged in with Angular 6!!
All signuped members:
- {{member.membername}} ({{member.memberFname}} {{member.memberLname}}) - Delete
Step 12: Angular 6 Home Component
Folder and File Path: /src/app/home/home.component.ts
import { Component, OnInit } from '@angular/core'; import { first } from 'rxjs/operators'; import { Member } from '../_models'; import { MemberService } from '../_services'; @Component({templateUrl: 'home.component.html'}) export class HomeComponent implements OnInit { currentMember: Member; members: Member[] = []; constructor(private memberService: MemberService) { this.currentMember = JSON.parse(localStorage.getItem('currentMember')); } ngOnInit() { this.loadAllMembers(); } deleteMember(id: number) { this.memberService.delete(id).pipe(first()).subscribe(() => { this.loadAllMembers() }); } private loadAllMembers() { this.memberService.getAll().pipe(first()).subscribe(members => { this.members = members; }); } }
Step 13: Angular 6 Login Component Template
Folder and File Path: /src/app/login/login.component.html
Login
Angular 6 Registration and Login System Example Tutorial From Scratch
Step 14: Angular 6 Login Component
Folder and File Path: /src/app/login/login.component.ts
import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { first } from 'rxjs/operators'; import { AlertService, AuthenticationService } from '../_services'; @Component({templateUrl: 'login.component.html'}) export class LoginComponent implements OnInit { loginForm: FormGroup; loading = false; submitted = false; returnUrl: string; constructor( private formBuilder: FormBuilder, private route: ActivatedRoute, private router: Router, private authenticationService: AuthenticationService, private alertService: AlertService) {} ngOnInit() { this.loginForm = this.formBuilder.group({ membername: ['', Validators.required], password: ['', Validators.required] }); this.authenticationService.logout(); this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/'; } get f() { return this.loginForm.controls; } onSubmit() { this.submitted = true; if (this.loginForm.invalid) { return; } this.loading = true; this.authenticationService.login(this.f.membername.value, this.f.password.value) .pipe(first()) .subscribe( data => { this.router.navigate([this.returnUrl]); }, error => { this.alertService.error(error); this.loading = false; }); } }
Step 15: Angular 6 SignUp Component Template
Folder and File Path: /src/app/signup/signup.component.html
SignUp
Angular 6 Registration and Login System Example Tutorial From Scratch
Step 16: Angular 6 SignUp Component
Folder and File Path: /src/app/signup/signup.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { first } from 'rxjs/operators'; import { AlertService, MemberService } from '../_services'; @Component({templateUrl: 'signup.component.html'}) export class SignUpComponent implements OnInit { signupForm: FormGroup; loading = false; submitted = false; constructor( private formBuilder: FormBuilder, private router: Router, private memberService: MemberService, private alertService: AlertService) { } ngOnInit() { this.signupForm = this.formBuilder.group({ memberFname: ['', Validators.required], memberLname: ['', Validators.required], membername: ['', Validators.required], password: ['', [Validators.required, Validators.minLength(6)]] }); } get f() { return this.signupForm.controls; } onSubmit() { this.submitted = true; if (this.signupForm.invalid) { return; } this.loading = true; this.memberService.signup(this.signupForm.value) .pipe(first()) .subscribe( data => { this.alertService.success('Registration successful', true); this.router.navigate(['/login']); }, error => { this.alertService.error(error); this.loading = false; }); } }
Step 17: Angular 6 App Component Template
Folder and File Path: /src/app/app.component.html
Step 18: Angular 6 App Component
Folder and File Path: /src/app/app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app', templateUrl: 'app.component.html' }) export class AppComponent { }
Step 19: Angular 6 App Module
Folder and File Path: /src/app/app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { ReactiveFormsModule } from '@angular/forms'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { fakeBackendProvider } from './_helpers'; import { AppComponent } from './app.component'; import { routing } from './app.routing'; import { AlertComponent } from './_directives'; import { AuthGuard } from './_guards'; import { JwtInterceptor, ErrorInterceptor } from './_helpers'; import { AlertService, AuthenticationService, MemberService } from './_services'; import { HomeComponent } from './home'; import { LoginComponent } from './login'; import { SignUpComponent } from './signup'; @NgModule({ imports: [ BrowserModule, ReactiveFormsModule, HttpClientModule, routing ], declarations: [ AppComponent, AlertComponent, HomeComponent, LoginComponent, SignUpComponent ], providers: [ AuthGuard, AlertService, AuthenticationService, MemberService, { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, fakeBackendProvider ], bootstrap: [AppComponent] }) export class AppModule { }
Step 20: Angular 6 App Routing
Folder and File Path: /src/app/app.routing.ts
import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } from './home'; import { LoginComponent } from './login'; import { SignUpComponent } from './signup'; import { AuthGuard } from './_guards'; const appRoutes: Routes = [ { path: '', component: HomeComponent, canActivate: [AuthGuard] }, { path: 'login', component: LoginComponent }, { path: 'signup', component: SignUpComponent }, // otherwise redirect to home { path: '**', redirectTo: '' } ]; export const routing = RouterModule.forRoot(appRoutes);
Step 21: Angular 6 Main Index Html File
Folder and File Path: /src/index.html
Angular 6 Registration and Login System Example Tutorial From Scratch a { cursor: pointer } Loading... Angular 6 Registration and Login System Example Tutorial From Scratch
Step 22: Angular 6 Main (Bootstrap) File
Folder and File Path: /src/main.ts
import './polyfills'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; platformBrowserDynamic().bootstrapModule(AppModule);
Step 23: Angular 6 Polyfills
Folder and File Path: /src/polyfills.ts
import 'core-js/es6/reflect'; import 'core-js/es7/reflect'; import 'zone.js/dist/zone';
Step 24: Angular 6 Custom Typings File
Folder and File Path: /src/typings.d.ts
//// Angular 6 Registration and Login System Example Tutorial From Scratch declare var config: any;
Step 25: npm package.json
Folder and File Path: /package.json
{ "name": "angular-6-registration-login-example-webpack", "version": "1.0.0", "repository": { "type": "git", "url": "https://github.com/cornflourblue/angular-6-registration-login-example-webpack.git" }, "scripts": { "build": "webpack --mode production", "start": "webpack-dev-server --mode development --open" }, "license": "MIT", "dependencies": { "@angular/common": "^6.0.0", "@angular/compiler": "^6.0.0", "@angular/core": "^6.0.0", "@angular/forms": "^6.0.0", "@angular/platform-browser": "^6.0.0", "@angular/platform-browser-dynamic": "^6.0.0", "@angular/router": "^6.0.0", "core-js": "^2.5.5", "rxjs": "^6.1.0", "zone.js": "^0.8.26" }, "devDependencies": { "@types/node": "^10.0.4", "angular2-template-loader": "^0.6.2", "html-webpack-plugin": "^3.2.0", "raw-loader": "^0.5.1", "ts-loader": "^4.3.0", "typescript": "^2.8.3", "webpack": "4.8.1", "webpack-cli": "^2.1.3", "webpack-dev-server": "3.1.4" } }
Step 26: TypeScript tsconfig.json
Folder and File Path: /tsconfig.json
{ "compilerOptions": { "emitDecoratorMetadata": true, "experimentalDecorators": true, "lib": [ "es2015", "dom" ], "module": "commonjs", "moduleResolution": "node", "noImplicitAny": true, "sourceMap": true, "suppressImplicitAnyIndexErrors": true, "target": "es5" } }
Step 27: Webpack 4 Config
Folder and File Path: /webpack.config.js
Angular 6 Registration and Login System Example Tutorial From Scratch
webpack is a static module bundler for modern JavaScript applications
const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/main.ts', module: { rules: [ { test: /\.ts$/, use: ['ts-loader', 'angular2-template-loader'], exclude: /node_modules/ }, { test: /\.(html|css)$/, loader: 'raw-loader' }, ] }, resolve: { extensions: ['.ts', '.js'] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html', filename: 'index.html', inject: 'body' }), new webpack.DefinePlugin({ config: JSON.stringify({ apiUrl: 'http://localhost:4000' }) }) ], optimization: { splitChunks: { chunks: 'all', }, runtimeChunk: true }, devServer: { historyApiFallback: true } };
Angular 6 CRUD Operations Application Tutorials
- Angular 6 applications – Insert, Fetch , Edit – update , Delete Operations
- Angular 6 CRUD
- Angular 6 and ASP.NET Core 2.0 Web API
- Angular 6 features
- Angular 6 Form Validation
- Angular 6 – User Registration and Login
- Angularjs 6 User Registration and Login Authentication
- Angular 6 CLI Installation Tutorial With Example
- Angular 6 Toast Message Notifications From Scratch
Read :
Summary
You can also read about AngularJS, ASP.NET, VueJs, PHP.
I hope you get an idea about Angular 6 Registration and Login System Example Tutorial From Scratch.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.