aboutsummaryrefslogtreecommitdiff
path: root/src/app/components/login/login.component.ts
blob: edbc4610b07c22dffd91b608c00df24b9a520ce8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { Router } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { UserService } from 'src/app/services/user.service';
import { HttpErrorResponse } from '@angular/common/http';
import { ErrorBarComponent } from '../error-bar/error-bar.component';
import { TokenService } from 'src/app/services/token.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  @ViewChild(ErrorBarComponent) private _errorBar: ErrorBarComponent;
  private _title = 'Login';
  public loginUserFormGroup: FormGroup;

  constructor(private _titleService: Title, private _fb: FormBuilder, private _router: Router, private _userService: UserService, private _tokenService: TokenService) {
    this._titleService.setTitle(this._title);
  }

  ngOnInit(): void {
    this.loginUserFormGroup = this._fb.group({
      username: new FormControl('', [
        Validators.required
      ]),
      password: new FormControl('', [
        Validators.required
      ])
    });
  }

  onSubmit(): void {
    this._errorBar.hideError();
    this._userService.loginUserRequest(this.loginUserFormGroup).subscribe({
        next: (res: object) => {
          this._tokenService.setUserTokenToSessionStorage(res);
          this._router.navigate(['/']);
        },
        error: (err: HttpErrorResponse) => {
          this._errorBar.showError(err);
        }
    });
  }

  onRedirectRegister(): void {
    this._router.navigate(['/register']);
  }
}