]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/login/login.component.ts
Client: reactive forms
[github/Chocobozzz/PeerTube.git] / client / src / app / login / login.component.ts
1 import { Component, OnInit } from '@angular/core';
2 import { FormBuilder, FormGroup, Validators } from '@angular/forms';
3 import { Router } from '@angular/router';
4
5 import { AuthService, FormReactive } from '../shared';
6
7 @Component({
8 selector: 'my-login',
9 template: require('./login.component.html')
10 })
11
12 export class LoginComponent extends FormReactive implements OnInit {
13 error: string = null;
14
15 form: FormGroup;
16 formErrors = {
17 'username': '',
18 'password': ''
19 };
20 validationMessages = {
21 'username': {
22 'required': 'Username is required.',
23 },
24 'password': {
25 'required': 'Password is required.'
26 }
27 };
28
29 constructor(
30 private authService: AuthService,
31 private formBuilder: FormBuilder,
32 private router: Router
33 ) {
34 super();
35 }
36
37 buildForm() {
38 this.form = this.formBuilder.group({
39 username: [ '', Validators.required ],
40 password: [ '', Validators.required ],
41 });
42
43 this.form.valueChanges.subscribe(data => this.onValueChanged(data));
44 }
45
46 ngOnInit() {
47 this.buildForm();
48 }
49
50 login() {
51 this.error = null;
52
53 const { username, password } = this.form.value;
54
55 this.authService.login(username, password).subscribe(
56 result => this.router.navigate(['/videos/list']),
57
58 error => {
59 console.error(error.json);
60
61 if (error.json.error === 'invalid_grant') {
62 this.error = 'Credentials are invalid.';
63 } else {
64 this.error = `${error.json.error}: ${error.json.error_description}`;
65 }
66 }
67 );
68 }
69 }