代码之家  ›  专栏  ›  技术社区  ›  Pierrick Martellière

角度6类型错误:无法读取未定义的属性'username'

  •  0
  • Pierrick Martellière  · 技术社区  · 6 年前

    我刚开始学习Angular6,开始学习AngularGetStarted教程。

    但是,在本教程中没有解释我在本例中要做什么。

    我希望能够用模板中的表单填充一个实体,将这个填充的实体发送到我的API的用户注册方法。

    我在标题中得到错误:(与nmuser.username或nmuser.username相同的错误)

    类型错误:无法读取未定义的属性“username”

    我做错什么了?

    这是我的模板:

    <ion-content>
      <ion-list>
    
        <ion-item>
          <ion-label color="orange" floating>Pseudo</ion-label>
          <ion-input [(ngModel)]="NmUser.username" type="text" name="pseudo"></ion-input>
        </ion-item>
    
        <ion-item>
          <ion-label color="orange" floating>Email</ion-label>
          <ion-input [(ngModel)]="nmUser.email" type="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$"></ion-input>
        </ion-item>
    
        <ion-item>
          <ion-label color="orange" floating>Mot de passe</ion-label>
          <ion-input [(ngModel)]="nmUser.password" color="orange" type="password" name="password" pattern=".{6,}"></ion-input>
        </ion-item>
    
        <ion-item style="margin-top: 5%" no-lines>
          <ion-label color="orange">Lieu de travail</ion-label>
          <ion-select [(ngModel)]="nmUser.workplace">
            <ion-option value="Mc_Donald's_Monaco">McDo Monaco</ion-option>
            <ion-option value="BK_Monaco">BK Monaco</ion-option>
            <ion-option value="SoGreen">SoGreen</ion-option>
            <ion-option value="Decathlon">Decathlon</ion-option>
            <ion-option value="La_Boule_Noire">La Boule Noire</ion-option>
            <ion-option value="High_Club">High Club</ion-option>
          </ion-select>
        </ion-item>
    
        <ion-item>
          <ion-label color="orange" floating>Intitulé du poste</ion-label>
          <ion-input [(ngModel)]="nmUser.job" color="orange" type="text" name="job"></ion-input>
        </ion-item>
    
        <ion-item style="margin-top: 5%" no-lines>
          <ion-label color="orange">Afficher mon lieu de travail</ion-label>
          <ion-toggle [(ngModel)]="nmUser.showJob"></ion-toggle>
        </ion-item>
    
        <ion-item style="margin-top: 5%" no-lines>
          <ion-label color="orange">Recevoir des emails automatiques</ion-label>
          <ion-toggle></ion-toggle>
        </ion-item>
    
        <ion-item style="margin-top: 5%" no-lines>
          <ion-label color="orange">J'ai lu et j'accepte les <span class="cgu">CGU</span></ion-label>
          <ion-toggle></ion-toggle>
        </ion-item>
    
        <ion-item style="margin-top: 5%" no-lines>
          <button ion-button color="orange" outline block large style="margin-top: 5%;" (click)="register()">S'inscrire</button>
        </ion-item>
    
      </ion-list>
    </ion-content>
    

    这是我的注册页面:

    import { Component } from '@angular/core';
    import { NavController } from 'ionic-angular';
    import { NmUserService } from '../../app/entities/nmUser/nmUser.service';
    import { NmUser } from './nmUser';
    
    @Component({
      selector: 'page-register',
      templateUrl: 'register.html',
      providers: [NmUserService]
    })
    export class RegisterPage {
    
      constructor(private navCtrl: NavController, private userService: NmUserService) {
    
      }
    
      register(user: NmUser): void {
        this.userService.add(user).subscribe(
            (result) => {
                // This code will be executed when the HTTP call returns successfully
            },
            (error) => {
                console.log(error);
            }
        );
      }
    
    }
    

    这是我的用户服务:

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpResponse, HttpErrorResponse, HttpHeaders} from '@angular/common/http';
    import { MessageService } from '../../message.service';
    import { NmUser } from './nmUser';
    import { Observable } from 'rxjs/Rx';
    import { catchError, map } from 'rxjs/operators';
    import 'rxjs/add/observable/throw';
    
    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json' })
    };
    
    @Injectable()
    export class NmUserService {
    
        private userUrl = 'http://my-api.com/api/user/';
    
        constructor(private http: HttpClient, private messageService : MessageService) {}
    
        /**
         * Create the passe nmUser.
         */
        add(nmUser : NmUser) : Observable<NmUser> {
            let body = nmUser;
    
            return this.http.post(this.userUrl, body)
                .pipe(
                    map(response => new NmUser(response)),
                    catchError(this.handleError)
                );
        }
    }
    

    这是我的用户实体:

    import {NmWorkplace} from '../nmWorkplace/nmWorkplace';
    
    export class NmUser {
        // Raw attributes
        id : number;
        email : string;
        username : string;
        profileImageUrl : string;
        password : string;
        job : string;
        showJob : boolean;
        note : number;
        points : number;
        roles : string;
        salt : string;
        status : string;
        createdAt : Date;
        updatedAt : Date;
        deletedAt : Date;
        notificationsActivated : boolean;
        connected : boolean;
        // x-to-one
        workplace : NmWorkplace;
    }
    

    任何帮助都将不胜感激。

    谢谢!

    3 回复  |  直到 6 年前
        1
  •  1
  •   maury844    6 年前

    您正在引用[(ngmodel)]中的nmuser,但您的component.ts中没有定义该变量,您需要在其中添加该声明。

    nmUser: NmUser;

    还要注意,在.html中,您正在调用 (click)=register() 没有任何参数,在.ts中,您希望用户 register(user: NmUser)

    另外,我不是100%确定,但我认为角鼓励使用 Reactive forms 从v4.0开始,用香蕉代替了ngmodel中的一个框[()]符号。

        2
  •  2
  •   Maryannah    6 年前

    这是组件的代码,不包含函数的内容:

    export class RegisterPage {
      constructor(private navCtrl: NavController, private userService: NmUserService) {}
      register(user: NmUser): void {}
    }
    

    在模板中,您尝试使用类成员:

    <ion-input [(ngModel)]="NmUser.username" type="text" name="pseudo"></ion-input>
    

    但是 NmUser 未定义(您的组件中没有),因此可以解释您的错误。

        3
  •  0
  •   Sh. Pavel    6 年前

    尝试以下操作:

    1. 在组件中添加nmuser声明,如下所示:

    nmuser:nmuser=new nmuser(…您的构造函数参数…);

    1. 在HTML标记中,尝试使用

    this.nmuser.用户名

    而不是

    nmuser.用户名

    在你的NGmodel中