无法读取未定义的Angular输入表单的属性“名称”

时间:2017-07-17 02:58:15

标签: angular typescript

我正在使用我从Angular Tutorial中学到的东西来制作一个简单的组件。我的组件通过服务调用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

1 个答案:

答案 0 :(得分:1)

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

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

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