首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular Update表单填充了输入字段,但仍然在控制台中返回错误?

Angular Update表单填充了输入字段,但仍然在控制台中返回错误?
EN

Stack Overflow用户
提问于 2018-05-14 09:21:26
回答 4查看 107关注 0票数 0

我正在尝试在Angular中创建一个更新表单。我尝试过很多东西,但我还是不太熟悉Angular。这看起来非常简单,我使用ngOnInit()方法获取数据(它返回正确的数据)。用户数据显示在输入字段中,但随后出现错误。

这是我在控制台中得到的错误:

代码语言:javascript
复制
UpdateComponent.html:6 ERROR TypeError: Cannot read property 'firstName' of undefined
    at Object.eval [as updateDirectives] (UpdateComponent.html:6)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:11914)
    at checkAndUpdateView (core.js:11307)
    at callViewAction (core.js:11548)
    at execComponentViewsAction (core.js:11490)
    at checkAndUpdateView (core.js:11313)
    at callViewAction (core.js:11548)
    at execEmbeddedViewsAction (core.js:11511)
    at checkAndUpdateView (core.js:11308)
    at callViewAction (core.js:11548)

我的update.component.html文件:

代码语言:javascript
复制
<div>
<h2 class="page-header">Edit your Profile</h2>
<form (ngSubmit)="onUpdateSubmit(user)" novalidate>
  <div class="form-group">
    <label for="firstName">First Name</label>
    <input type="text" [(ngModel)]="user.firstName" name="firstName" class="form-control" id="firstName" placeholder="First Name">
  </div>
  <div class="form-group">
    <label for="lastName">Last Name</label>
    <input type="text" [(ngModel)]="user.lastName" name="lastName" class="form-control" id="lastName" placeholder="Last Name">
  </div>
  <div class="form-group">
    <label for="age">Age</label>
    <input type="number" [(ngModel)]="user.age" name="age" class="form-control" id="age" placeholder="Age" min="0" max="200">
  </div>
  <div class="form-group">
    <label for="favoriteFood">What is your Favorite Food?</label>
    <input type="text" [(ngModel)]="user.favoriteFood" name="favoriteFood" class="form-control" id="favoriteFood" placeholder="Favorite Food">
  </div>
  <div class="form-group">
    <label for="username">Username</label>
    <input type="text" [(ngModel)]="user.username" name="username" class="form-control" id="username" placeholder="Username">
  </div>
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <input type="email" [(ngModel)]="user.email" name="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
    <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" [(ngModel)]="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>
</div><div>
<h2 class="page-header">Edit your Profile</h2>
<form (ngSubmit)="onUpdateSubmit(user)" novalidate>
  <div class="form-group">
    <label for="firstName">First Name</label>
    <input type="text" [(ngModel)]="user.firstName" name="firstName" class="form-control" id="firstName" placeholder="First Name">
  </div>
  <div class="form-group">
    <label for="lastName">Last Name</label>
    <input type="text" [(ngModel)]="user.lastName" name="lastName" class="form-control" id="lastName" placeholder="Last Name">
  </div>
  <div class="form-group">
    <label for="age">Age</label>
    <input type="number" [(ngModel)]="user.age" name="age" class="form-control" id="age" placeholder="Age" min="0" max="200">
  </div>
  <div class="form-group">
    <label for="favoriteFood">What is your Favorite Food?</label>
    <input type="text" [(ngModel)]="user.favoriteFood" name="favoriteFood" class="form-control" id="favoriteFood" placeholder="Favorite Food">
  </div>
  <div class="form-group">
    <label for="username">Username</label>
    <input type="text" [(ngModel)]="user.username" name="username" class="form-control" id="username" placeholder="Username">
  </div>
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <input type="email" [(ngModel)]="user.email" name="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
    <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" [(ngModel)]="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>

我的update.component.ts文件:

代码语言:javascript
复制
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { ValidateService } from '../../services/validate.service';
import { Router } from "@angular/router";
import { FlashMessagesService } from 'angular2-flash-messages';

@Component({
  selector: 'app-update',
  templateUrl: './update.component.html',
  styleUrls: ['./update.component.css']
})
export class UpdateComponent implements OnInit {
  user: Object;

  constructor(
    private authService: AuthService,
    private validateService: ValidateService,
    private router: Router,
    private _flashMessagesService: FlashMessagesService
  ) { }

  ngOnInit() {
    this.authService.getProfile().subscribe(profile => {
      this.user = profile.user;
    },
    err => {
      console.log(err);
      return false;
    });
  }

  onUpdateSubmit(user) {
    console.log("Component", user)
    // Required Fields
    if(!this.validateService.validateSignup(user)) {
      this._flashMessagesService.show("Please fill in all fields", {cssClass: "alert-danger", timeout: 3000});
      return false;
    }

    // Validate Email
    if(!this.validateService.validateEmail(user.email)) {
      this._flashMessagesService.show("Please use valid email", {cssClass: "alert-danger", timeout: 3000});
      return false;
    }

    // Update user
    this.authService.updateUser(user).subscribe(data => {
      if(data.success) {
        this._flashMessagesService.show("Update Success!", {cssClass: "alert-success", timeout: 3000});
        this.router.navigate(["/profile"]);
      } else {
        this._flashMessagesService.show("Something went wrong", {cssClass: "alert-danger", timeout: 3000});
        this.router.navigate(["/update"]);
      }
    });
  }

}
EN

回答 4

Stack Overflow用户

发布于 2018-05-14 09:44:50

这是因为用户数据中没有返回firstName。也许它是未定义的。来避免这个问题。

最好: 1.如果返回,请检查ngOnInit()中的用户数据。2.初始用户数据。e,g:user = { firstName: '' }; 3.从业务获取用户数据是否有延迟

票数 1
EN

Stack Overflow用户

发布于 2018-05-14 09:53:36

你的表单中有一个双向绑定,那么为什么你需要在表单提交时传递给用户。尝试使用下面的方法

代码语言:javascript
复制
   <form (ngSubmit)="onUpdateSubmit()" novalidate>
    .
    .
    .

并使用

代码语言:javascript
复制
  onUpdateSubmit() {
    console.log("Component", this.user);
    .
    .
    .
 }
票数 0
EN

Stack Overflow用户

发布于 2018-05-14 09:55:19

您的错误消息很清楚。您的用户是由ngOnInit上的api调用填充的,但是,它可能会在加载html后返回响应。加载时,您的DOM期望用户可用,但在您的情况下它是未定义的。有几种方法可以解决这个问题。首先,遵循通常的标准,在构造函数中定义你的用户,如下所示。

代码语言:javascript
复制
constructor(
    private authService: AuthService,
    private validateService: ValidateService,
    private router: Router,
    private _flashMessagesService: FlashMessagesService
  ) { 

   this.user = <Object>{};
}

现在您的用户不是未定义的,即使user.name可能是未定义的,它也将是简短的,并且不会抛出错误。第二种选择是,更新你的update.component.html,只有当用户可用或未定义时才加载你的DOM。为此,请在第一个div中添加*ngIf

代码语言:javascript
复制
<div *ngIf="user">
<h2 class="page-header">Edit your Profile</h2>
<form (ngSubmit)="onUpdateSubmit(user)" novalidate>
........
.........
</form
</div>

如上所述,当用户未定义时,您的表单将不会被加载,从而避免了对user.name的需要。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50322060

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档