Skip to content

Instantly share code, notes, and snippets.

@4skinSkywalker
Last active March 28, 2019 15:12
Show Gist options
  • Save 4skinSkywalker/1aeac02b2a966584490b28ec23a709cc to your computer and use it in GitHub Desktop.
Save 4skinSkywalker/1aeac02b2a966584490b28ec23a709cc to your computer and use it in GitHub Desktop.
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