0

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">

2 Answers 2

3

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);
});
Sign up to request clarification or add additional context in comments.

15 Comments

Thank you it works. But now i have the same issue that the begining "ERROR 400 Bad request" I don't know where is the problem, if Im sending wrong request or if i made something wrong when i coded it. Request URL: my-url.com/login Request Method: OPTIONS Status Code: 400 Bad Request Remote Address: 52.209.88.81:443 Referrer Policy: no-referrer-when-downgrade
@CorentinBetz Maybe you have more fields in your form? what is the request it is sending, and what is the back end expecting? Also, I would recommend instead of ngForm creating a formGroup and using the formGroup's value for this.user, so you know exactly what is defined.
I've checked the console.log(user.username) and it display : undefined (instead of username) Password (it's works for the password)
@CorentinBetz If you want to edit your question to include the html, I will edit my answer to include a FormGroup
@CorentinBetz Edited to add support for Angular forms (also included example validation for no reason at all).... This is a much better pattern.
|
0

You have to inilialize user.

Replace user: User; by user: User= new User or user: User = {};

1 Comment

user: User = {}; Will give a type Error

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.