import { Router } from '@angular/router' ; import { FormBuilder , FormGroup , Validators } from '@angular/forms' ; import { Component } from '@angular/core' ; import { Observable } from 'rxjs/Observable' ; import { UserService } from './../../../core/services' ; @ Component ( { templateUrl : './login.component.html' } ) export class LoginComponent { loginForm : FormGroup ; constructor ( private fb , private us , private router ) { this . loginForm = this . fb . group ( { username : [ '' , Validators . required ] , password : [ '' , Validators . required ] } ) ; } submitForm ( ) { this . loginForm . markAsPending ( ) ; const formData = { username : this . loginForm . value . username , password : this . loginForm . value . password , } ; this . us . login ( formData ) . first ( ) . catch ( ( err ) => { let formError ; if ( err . status === 401 ) { formError = { wrongPassword : 'Username or password is wrong' } ; } else { formError = { formError : 'There was an error during login' } ; } this . loginForm . setErrors ( formError ) ; return Observable . throw ( new Error ( err ) ) ; } ) . subscribe ( res => { this . us . setUserData ( ) ; this . router . navigate ( [ '/' ] ) ; } ) ; } }