1
|
import {Component, OnInit} from '@angular/core';
|
2
|
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
|
3
|
import {switchMap} from 'rxjs/operators';
|
4
|
import {of, Subscription} from 'rxjs';
|
5
|
import {AuthService} from '../../auth/services/auth.service';
|
6
|
import {Router} from '@angular/router';
|
7
|
|
8
|
@Component({
|
9
|
selector: 'app-login',
|
10
|
templateUrl: './login.component.html',
|
11
|
styleUrls: ['./login.component.scss']
|
12
|
})
|
13
|
export class LoginComponent implements OnInit {
|
14
|
|
15
|
loginForm: FormGroup;
|
16
|
subscription: Subscription[] = [];
|
17
|
|
18
|
constructor(
|
19
|
private formBuilder: FormBuilder,
|
20
|
private authService: AuthService,
|
21
|
private router: Router
|
22
|
) {
|
23
|
}
|
24
|
|
25
|
ngOnInit(): void {
|
26
|
this.loginForm = this.formBuilder.group({
|
27
|
username: ['', [Validators.required]],
|
28
|
password: ['', Validators.required]
|
29
|
});
|
30
|
this.userRedirect();
|
31
|
}
|
32
|
|
33
|
doLogin(): void {
|
34
|
if (this.loginForm.valid) {
|
35
|
this.subscription[2] = this.authService.doLogin({
|
36
|
username: this.loginForm.controls.username.value,
|
37
|
password: this.loginForm.controls.password.value
|
38
|
})
|
39
|
.pipe(
|
40
|
switchMap(res => {
|
41
|
console.log(res);
|
42
|
if (res) {
|
43
|
console.log('Login getUserState');
|
44
|
return this.authService.getUserState();
|
45
|
} else {
|
46
|
return of(false);
|
47
|
}
|
48
|
})
|
49
|
).subscribe(
|
50
|
res => {
|
51
|
console.log(res);
|
52
|
if (res) {
|
53
|
this.subscription[2].unsubscribe();
|
54
|
this.router.navigate(['/dashboard'])
|
55
|
}
|
56
|
}
|
57
|
);
|
58
|
}
|
59
|
}
|
60
|
|
61
|
userRedirect(): void {
|
62
|
console.log('Login redirect');
|
63
|
if (this.authService.getUser()){
|
64
|
console.log('Redirect to dashboard!');
|
65
|
this.router.navigate(['/dashboard']);
|
66
|
}
|
67
|
}
|
68
|
}
|