import { Component , OnInit } from '@angular/core' ; import { AbstractControl , FormBuilder , FormGroup , Validators } from '@angular/forms' ; import { ActivatedRoute , Router } from '@angular/router' ; import { first } from 'rxjs/operators' ; import { AlertService } from '../alert/alert.service' ; import { AuthenticationService } from '../auth/authentication.service' ; @ Component ( { templateUrl : 'login.component.html' } ) export class LoginComponent implements OnInit { loginForm : FormGroup ; loading = false ; submitted = false ; constructor ( private formBuilder , private route , private router , private authenticationService , private alertService ) { if ( this . authenticationService . currentUserValue ) { this . router . navigate ( [ '/home' ] ) ; } } ngOnInit ( ) { this . loginForm = this . formBuilder . group ( { username : [ '' , Validators . required ] , password : [ '' , Validators . required ] , } ) ; } get f ( ) : { [ p ] : AbstractControl ; } { return this . loginForm . controls ; } onSubmit ( ) { this . submitted = true ; if ( this . loginForm . invalid ) { return ; } this . loading = true ; this . authenticationService . login ( this . f . username . value , this . f . password . value ) . pipe ( first ( ) ) . subscribe ( ( ) => { this . router . navigate ( [ '/home' ] ) ; } , ( { error = { } } ) => { console . log ( '==' , error ) ; const { message } = error ; this . alertService . error ( message ) ; this . loading = false ; } ) ; } }