### File

`src/app/Views/login/login.component.ts`

### Metadata

selector | `app-login`
styleUrls | `login.component.scss`
templateUrl | `login.component.html`

### Constructor

`constructor(authService: AuthService, tokenStorage: TokenStorageService, router: Router)`

Parameters :

- privateauthService : `AuthService`
- privatetokenStorage : `TokenStorageService`
- privaterouter : `Router`

### Methods

onSubmit
`onSubmit()`
Returns: `void`

reloadPage
`reloadPage()`
Returns: `void`

### Properties

accountName
`accountName: `string` </bcode>`

errorMessage
`errorMessage: `string` </bcode>`

form
`form: `any` </bcode>`

isLoggedIn
`isLoggedIn: `boolean` </bcode>`
Default value: `false`

isLoginFailed
`isLoginFailed: `boolean` </bcode>`
Default value: `false`

    import { Component, OnInit } from '@angular/core';
    import { AuthService } from '../../Services/auth.service';
    import { TokenStorageService } from '../../Services/token.service';
    import { Router } from '@angular/router';

    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.scss'],
    })
    export class LoginComponent implements OnInit {
      form: any = {
        email: null,
        password: null,
      };

      isLoggedIn = false;
      isLoginFailed = false;
      errorMessage = '';
      accountName = '';

      /**
       * @param  {AuthService} privateauthService
       * @param  {TokenStorageService} privatetokenStorage
       * @param  {Router} privaterouter
       */
      constructor(
        private authService: AuthService,
        private tokenStorage: TokenStorageService,
        private router: Router
      ) {}

      //ngOnInit() checks if a user is logged in
      ngOnInit(): void {
        this.tokenStorage.signOut();
        if (this.tokenStorage.getToken()) {
          this.isLoggedIn = true;
        }
      }

      //onSubmit() saves valuable information in session storage
      onSubmit(): void {
        const { email, password } = this.form;
        this.authService.login(email, password).subscribe(
          (data) => {
            this.tokenStorage.saveToken(data.data.token);
            this.tokenStorage.saveUser(data.data);

            this.isLoginFailed = false;
            this.isLoggedIn = true;
            this.accountName = email;
            this.router.navigate(['']);
          },
          (err) => {
            this.errorMessage = err.error.message;
            this.isLoginFailed = true;
          }
        );
      }

      //reloadPage() reloads the page
      reloadPage(): void {
        window.location.reload();
      }
    }

# results matching ""

# No results matching ""