angularauthenticationpostangular-httpclient

ERROR TypeError: Cannot set property 'username' of undefined


I need to request my API (https://myurl.com/login) for login (username + password) in angular 7.3. When i use POST without user.models.ts I received a bad request error. When I use this model I have this error:

"ERROR TypeError: Cannot set property 'username' of undefined."

user.model.ts

export class User {
constructor(public username: string,
            public password: string) {
    }
}

login.component.ts:

import {Component, OnInit} from '@angular/core';
import {NgForm} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
import {LoginService} from '../services/login.service';
import {User} from '../models/user.model';


@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
    user: User;
    constructor(private httpClient: HttpClient, private loginService: 
LoginService) { }
    ngOnInit() {
    }
    onSubmit(form: NgForm) {
        this.user.username = form.value['login'];
        this.user.password = form.value['password'];
        this.loginService.LoginUser(this.user).subscribe(res => {
            console.log(res);
        });
    }
}

login.service.ts:

import {User} from '../models/user.model';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import {Injectable} from '@angular/core';

@Injectable()
export class LoginService {
    constructor(private http: HttpClient) { }

    LoginUser(user: User): Observable<User> {
        return this.http.post<User>('https://captn-boat-api.herokuapp.com/login', user)
        ;
    }
}    

login.component.html

<div class="login--already-registered">
      <span class="login--screen-title">J'ai déjà un compte</span>

      <form class="login" method="GET" action="login" (ngSubmit)="onSubmit(f)" #f="ngForm">

        <div class="input--field text dark">
          <label for="login" class="control-label"><svg class="icon icon-envelope"><use xlink:href="#icon-envelope"></use></svg> E-mail</label>
          <input id="login" name="login" type="text" placeholder="" value="" ngModel>

        </div>

        <div class="input--field password dark">
          <label for="password" class="control-label"><svg class="icon icon-lock"><use xlink:href="#icon-lock"></use></svg> Mot de passe</label>
          <input id="password" name="password" type="password" placeholder="" value="" ngModel>

        </div>

        <div class="input--field checkbox dark">
          <label for="session"><input id="session" name="" value="session" type="checkbox"> se souvenir de moi</label>
        </div>

        <div class="login--submit">

          <button class="button button btn-submit" type="submit">

Solution

  • You never instantiate user..... You can change your onSubmit as follows

    instead of:

    this.user.username = form.value['login'];
    this.user.password = form.value['password'];
    

    do this....

    this.user = new User(form.value['login'], form.value['password']);
    

    but do you really need the User class? why not just define an IUser interface instead of a User class and do...

    this.user = form.value;
    this.loginService.LoginUser(this.user).subscribe(res => {
            console.log(res);
        });
    

    Best way, with formGroup....

    in the html.... make the following changes (this includes required validation for username and password, and disabled submit button if form is invalid)....

    <form class="login" method="GET" action="login" (ngSubmit)="onSubmit(f)" [formGroup]="formGroup">
    
    <input id="login" name="login" type="text" formControlName="username">
    <input id="password" name="password" type="password" formControlName="password">
    
    <button class="button button btn-submit" type="submit" [disabled]="!formGroup.valid">
    

    Then, in the component ts file....

    formGroup: FormGroup = new FormGroup({
        username: new FormControl(null, Validators.required),
        password: new FormControl(null, Validators.required)
    });
    

    and in your OnSubmit function....

    this.user = this.formGroup.value;
    this.loginService.LoginUser(this.user).subscribe(res => {
        console.log(res);
    });