【问题标题】:Cannot read property 'name' of undefined Angular input-form无法读取未定义的 Angular 输入表单的属性“名称”
【发布时间】:2017-12-21 11:10:01
【问题描述】:

我正在使用从 Angular 教程中学到的知识来制作一个简单的组件。我的组件通过服务调用 UserService 从 angular-in-memory-web-api 获取数据。然后我添加输入表单来创建新用户。 当我单击添加按钮时出现错误,来自 UserService 的响应无法添加新用户(名称,地址)(如果我在这里错了,请原谅),因此无法传回 html 文件的数据。 我该如何解决?任何建议将不胜感激。

user.service.ts

import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptions, Response } from '@angular/http';

import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';

import { User } from './user';

@Injectable()
export class UserService {
  private usersUrl = 'api/users';

  private headers = new Headers({'Content-Type': 'application/json'});
  private options = new RequestOptions({ headers: this.headers });

  constructor(private http: Http) { }

  getUsers(): Observable<User[]> {
    return this.http.get(this.usersUrl)
                .map(response => response.json().data as User[])
                .catch(this.handleError);
  }

  addUser(user: User): Observable<string> {
      return this.http.post(this.usersUrl,
          JSON.stringify({ name: user.name,
              address: user.address
          }),
          this.options)
          .map(res => res.json().data as User)
          .catch(this.handleError);
  }



  private handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
      }
      console.error(errMsg);
      window.alert(errMsg);
      return Observable.throw(errMsg);
    }
}

home.component.ts

import { Component, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';


import { User } from '../user';
import { UserService } from '../user.service';


@Component({
  selector: 'app-home',
  templateUrl: 'home.component.html'
})

export class HomeComponent implements OnInit {

  user: any ={};
  users: User[];


  constructor(
    private userService: UserService,
    private http: Http
  ) {
  }

  getUsers(): void {
    this.userService.getUsers().subscribe(users => this.users = users);
  }

  add(user: User) {
    this.userService.addUser(this.user)
      .subscribe(
      user => {
        this.users.push(user);
        console.log(JSON.stringify(user))
      }
      );
    console.log(this.user);
  }




  ngOnInit(): void {
    this.getUsers();
  }
}

home.component.html

<form name="form" #f="ngForm" (ngSubmit)="add()">
  <input type="text" name="userName" [(ngModel)]="user.name"
  #name="ngModel" />

  <input type="text" name="userAddress" [(ngModel)]="user.address"
  #address="ngModel" />

  <button id="addbutton" type="submit"> Add </button>
</form>



<div>
    <h2>Data</h2>
    <div *ngFor="let user of users">
      <input [(ngModel)]="user.name"/>
      <input [(ngModel)]="user.address"/>
    </div>
</div>

Error

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您的组件中没有用户对象。在表单中使用它之前创建一个。

    public user:User = {
        name:'',
        address: ''
    }; // initialize to empty user . 
    

    当您使用 ngModel 时,这是双向数据绑定。所以它试图评估初始值。在您的情况下,您给出了 user.name 但没有名为 user 的对象,因此它的值是 undefined ,因此出现错误

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-22
      • 2021-08-16
      • 2019-09-06
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 2019-09-14
      相关资源
      最近更新 更多