Last active
March 28, 2019 15:12
-
-
Save 4skinSkywalker/1aeac02b2a966584490b28ec23a709cc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, OnInit } from '@angular/core' | |
import { Router } from '@angular/router' | |
import { tap, catchError } from 'rxjs/operators' | |
import { throwError } from 'rxjs' | |
@Component({ | |
selector: 'app-login', | |
templateUrl: './login.component.html', | |
styleUrls: ['./login.component.css'] | |
}) | |
export class LoginComponent implements OnInit { | |
isInvalid: boolean = false | |
constructor( | |
private http: HttpClient, | |
private router: Router) { } | |
ngOnInit() { | |
} | |
submit(f) { | |
const credentials: f.value | |
this.http.post('/api/authentication', credentials) | |
.pipe( | |
catchError(this.handleError), | |
tap(response => { | |
localStorage.setItem('token', response['token']) | |
}) | |
) | |
.subscribe(result => { | |
this.router.navigate(['']) | |
}, | |
error => { | |
if (error === 'Unauthorized.') { | |
this.isInvalid = true | |
} | |
}) | |
} | |
private handleError(error: HttpErrorResponse) { | |
if (error.error instanceof ErrorEvent) { | |
// Client-side or network error | |
} else { | |
// Unsuccessful response code | |
if (error.status === 401) { | |
return throwError( 'Unauthorized.' ) | |
} | |
} | |
return throwError( error.error ) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment