'How to login with email and password in angular typescript
I have an Angular app where user can login with his email and password. so at first i just want the login (login.component) page to appear first, when the user enters his email and password then we go directly to menu page (app.component), in the menu page we have LogOut so when the user click on it then return to login page.
This is what i do :
code :
login.component.html :
<h1 style="text-align:center">
<img src="../../assets/images/logo.png">
</h1>
<div class="login-wrap">
<div class="login-html">
<div class='login'>
<div class='col-md-4 offset-4 mt-5' *ngIf='!this.isLogin'>
<h2 class="login-header">S'identifier</h2>
<form class="login-container" #myform="ngForm" (ngSubmit)="onSubmit(myform)">
<div class='form-group'>
<input class='form-control' type="email" name="email" placeholder="email" ngModel>
</div>
<div class='form-group'>
<input class='form-control' type="password" name="password" placeholder="Password"
[type]="hide ? 'password': 'text'" [(ngModel)]="passwordValue">
<span class="material-icons" matSuffix (click)="hide = !hide">
{{hide ? 'visibility': 'visibility_off'}}
</span>
</div>
<input class='btn btn-outline-info' type="submit" value="Login">
</form>
</div>
<div class='col-md-4 offset-4 mt-5' *ngIf='this.isLogin'>
<h1>You are logged in</h1>
<button class='btn btn-outline-info' (click)='logout()'>Log-out</button>
</div>
</div>
</div>
</div>
login.component.ts :
export class LoginComponent implements OnInit {
isLogin: boolean = false
errorMessage: any
hide =true;
passwordValue='';
constructor(
private _api: ApiService,
private _auth: AuthService,
private _router:Router, private toastr : ToastrService) { }
ngOnInit(){
this.isUserLogin();
}
onSubmit(form: NgForm) {
console.log('Your form data : ', form.value);
this._api.postTypeRequest('user/login', form.value).subscribe((res: any) => {
switch (res.status) {
case 0:
this.toastr.error("you have a problem","Erreur");
break;
case 1:
this._auth.setDataInLocalStorage('userData', JSON.stringify(res.data));
this._auth.setDataInLocalStorage('token', res.token);
this._router.navigate(['']);
break;
case 2:
this.toastr.warning("your email or password is incorrect","Warning");
this.passwordValue = '';
break;
}
})
}
isUserLogin(){
if(this._auth.getUserDetails() != null){
this.isLogin = true;
}
}
logout(){
this._auth.clearStorage()
this._router.navigate(['']);
}
}
app.component.html (menu) :
<nav class="menu">
<ol>
<li class="menu-item"><a routerLink="adherents">Adherents</a></li>
<li class="menu-item">
<a routerLink="factures">Factures</a>
</li>
<li class="menu-item">
<a routerLink="logs">Logs</a>
</li>
<li class="menu-item">
<a routerLink="regions">Regions</a>
</li>
<li class="menu-item">
<a routerLink="roles">Roles</a>
</li>
<li class="menu-item">
<img class="img" src="../assets/images/user.png">
<a>welcome james</a>
<ol class="sub-menu">
<li class="menu-item"><a routerLink="/login">LogOut</a></li>
</ol>
</li>
</ol>
</nav>
<router-outlet></router-outlet>
auth-guard.service.ts :
@Injectable({
providedIn: 'root'
})
export class AuthGuardService {
constructor( private _authService: AuthService,
private _router: Router) { }
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (this._authService.getToken()) {
return true;
}
this._router.navigate(['/login']);
return false;
}
}
auth.service.ts:
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor() { }
getUserDetails() {
if(localStorage.getItem('userData')){
return localStorage.getItem('userData')
}else{
return null
}
}
setDataInLocalStorage(variableName, data) {
localStorage.setItem(variableName, data);
}
getToken() {
return localStorage.getItem('token');
}
clearStorage() {
localStorage.clear();
}
}
api.service.ts :
import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ApiService {
baseUrl = 'http://localhost:3000/';
constructor(private _http: HttpClient) { }
getTypeRequest(url) {
const headers = new HttpHeaders().set('Content-Type','application/json');
return this._http.get(`${this.baseUrl}${url}`, {headers}).pipe(map(res => {
return res;
}));
}
postTypeRequest(url, payload) {
const headers = new HttpHeaders().set('Content-Type','application/json');
return this._http.post(`${this.baseUrl}${url}`, payload, {headers}).pipe(map(res => {
return res;
}));
}
}
Solution 1:[1]
The question is not clear but I guess you just need to use logout() method in the app component the same way you are using it in the login component
<ol class="sub-menu">
<li class="menu-item"><a href="#" (click)="logout()>LogOut</a></li>
</ol>
Solution 2:[2]
You have to follow the below steps
- Replace app.component.html code like
Existing
<li class="menu-item"><a routerLink="/login">LogOut</a></li>
New
<li class="menu-item"><a href="#" (click)="logout()>LogOut</a></li>
- Paste the below code lines in app.component.ts
logout(){this._auth.clearStorage();this._router.navigate(['/login']);}
Check the constructor of app.component.ts and verify that there are the following lines added (similar to login.component.ts)
private _auth: AuthService, private _router:Router
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Merna Mustafa |
| Solution 2 | Anant Dhas |
