import { Router } from '@angular/router'; import { UserService } from './../user.service'; import { Component, OnInit, AfterViewInit, ViewChild, HostBinding } from '@angular/core'; import { routerTransition } from '../../animations/router.animations'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'], animations: [routerTransition()] }) export class LoginComponent implements AfterViewInit { @HostBinding('@routerTransition') transition; @ViewChild('mail') vc; user = { email: '', password: '' }; loading: boolean; loginError: string; constructor(private userService: UserService, private router: Router) { if (userService.loggedIn()) { this.redirect(); } } ngAfterViewInit() { setTimeout(() => this.vc.nativeElement.focus(), 100); } onSubmit() { this.loading = true; this.loginError = ''; this.userService.login(this.user.email, this.user.password) .then(() => this.redirect()) .catch((error: Error) => this.loginError = error.message) .then(() => this.loading = false); } redirect() { if (!!this.userService.redirectUrl) { this.router.navigate([this.userService.redirectUrl]); delete this.userService.redirectUrl; } else { this.router.navigate(['']); } } }