80 lines
2.0 KiB
TypeScript
80 lines
2.0 KiB
TypeScript
import { Component, OnInit, ViewChild, AfterViewInit } from "@angular/core";
|
|
import { Router, ActivatedRoute } from "@angular/router";
|
|
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
|
|
import { MatInput } from "@angular/material/input";
|
|
|
|
import { first } from "rxjs/operators";
|
|
|
|
import { AuthenticationService } from "../../services/authentication.service";
|
|
import { TranslateModule } from "@ngx-translate/core";
|
|
|
|
@Component({
|
|
selector: "app-login-user",
|
|
templateUrl: "./login-user.component.html",
|
|
styleUrls: ["./login-user.component.css"],
|
|
imports: [TranslateModule],
|
|
})
|
|
export class LoginUserComponent implements OnInit, AfterViewInit {
|
|
loginForm: FormGroup;
|
|
loading = false;
|
|
submitted = false;
|
|
returnUrl: string;
|
|
error = "";
|
|
@ViewChild("username") userNameInput: MatInput;
|
|
|
|
constructor(
|
|
private formBuilder: FormBuilder,
|
|
private route: ActivatedRoute,
|
|
private router: Router,
|
|
private authenticationService: AuthenticationService
|
|
) {
|
|
if (this.authenticationService.currentUserValue) {
|
|
this.router.navigate(["/"]);
|
|
}
|
|
}
|
|
|
|
ngAfterViewInit() {
|
|
this.userNameInput.focus();
|
|
}
|
|
|
|
ngOnInit() {
|
|
this.loginForm = this.formBuilder.group(
|
|
{
|
|
username: ["", [Validators.required, Validators.minLength(3)]],
|
|
password: ["", [Validators.required]],
|
|
},
|
|
{ updateOn: "submit" }
|
|
);
|
|
|
|
// get return url from route parameters or default to '/'
|
|
this.returnUrl = this.route.snapshot.queryParams["returnUrl"] || "/";
|
|
}
|
|
|
|
get formCtrls() {
|
|
return this.loginForm.controls;
|
|
}
|
|
|
|
onLoginSubmit() {
|
|
this.submitted = true;
|
|
|
|
if (this.loginForm.valid) {
|
|
this.loading = true;
|
|
this.authenticationService
|
|
.login(
|
|
this.formCtrls["username"].value,
|
|
this.formCtrls["password"].value
|
|
)
|
|
.pipe(first())
|
|
.subscribe(
|
|
(data) => {
|
|
this.router.navigate([this.returnUrl]);
|
|
},
|
|
(error) => {
|
|
this.error = error;
|
|
this.loading = false;
|
|
}
|
|
);
|
|
}
|
|
}
|
|
}
|