Login works

This commit is contained in:
Daniel 2024-10-31 23:53:01 -04:00
parent eb7ac86759
commit 4d402778b0
3 changed files with 21 additions and 20 deletions

View file

@ -1,8 +1,8 @@
import { Injectable } from '@angular/core';
import {HttpClient, HttpErrorResponse, HttpResponse } from '@angular/common/http';
import {HttpClient, HttpResponse } from '@angular/common/http';
import { Router } from '@angular/router';
import { catchError } from 'rxjs/operators';
import { Observable, ObservableInput } from 'rxjs';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
export class Jwt {
constructor(
@ -18,19 +18,12 @@ export class APIService {
}
login(failFunc: () => void, username: string, password: string) {
let ff = (err: any, caught: Observable<HttpResponse<Jwt>>): ObservableInput<any> => {
console.log(err);
failFunc();
return caught.pipe();
};
this.http.post<Jwt>('/login', {username: username, password: password}, {observe: 'response'}).pipe(catchError(ff)).subscribe(event => {
login(username: string, password: string): Observable<HttpResponse<Jwt>> {
return this.http.post<Jwt>('/login', {username: username, password: password}, {observe: 'response'}).pipe(tap((event) => {
if (event.status == 200) {
sessionStorage.setItem('jwt', event.body?.jwt.toString() ?? '');
this._router.navigateByUrl('/home');
} else {
failFunc();
}
});
}));
}
}

View file

@ -14,8 +14,8 @@
</div>
</div>
@if (failed) {
<div>
Login Failed
<div role="alert" class="alert alert-error">
<span>Login Failed!</span>
</div>
}
</div>

View file

@ -1,6 +1,8 @@
import { Component, inject } from '@angular/core';
import {FormsModule} from '@angular/forms';
import {APIService} from '../api.service';
import {catchError, of } from 'rxjs';
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
@ -11,16 +13,22 @@ import {APIService} from '../api.service';
})
export class LoginComponent {
apiService: APIService = inject(APIService);
router: Router = inject(Router);
username: string = '';
password: string = '';
failed: boolean = false;
failLogin() {
failed = true;
}
onSubmit() {
this.failed = false;
this.apiService.login(this.failLogin, this.username, this.password);
this.apiService.login(this.username, this.password).pipe(catchError(() => {
this.failed = true;
return of(null);
})).subscribe((event) => {
if (event?.status == 200) {
this.router.navigateByUrl('/home')
} else {
this.failed = true;
}
});
}
}