ERROR TypeError: Cannot set property 'username' of undefined

ERROR TypeError: Cannot set property 'username' of undefined

我需要在 angular 7.3 中请求我的 api (https://myurl.com/login) 登录(用户名 + 密码)。当我在没有 user.models.ts 的情况下使用 POST 时,我收到了错误的请求错误。当我使用这个模型时,我有这个错误:"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">

您永远不会实例化用户.....您可以按如下方式更改您的 onSubmit

而不是:

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

这样做....

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

但是您真的需要用户 class 吗?为什么不只定义一个 IUser 接口而不是一个 User class 并做...

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

最佳方式,使用 formGroup....

在 html... 中进行以下更改(这包括需要验证用户名和密码,如果表单无效则禁用提交按钮)...

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

然后,在组件ts文件中....

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

并在您的 OnSubmit 函数中....

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

您必须初始化 user

user: User;替换为user: User= new Useruser: User = {};