2017-07-17 41 views
0

我正在使用從Angular Tutorial中學到的知識來創建一個簡單的組件。我的組件通過服務調用UserService從角存儲器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

回答

0

你不必一個用戶對象在你身上r組件。在形式中使用它之前創建一個。

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

當您使用ngModel時,這是雙向數據綁定。所以它試圖評估初始值。在你的情況下,你給了user.name,但沒有名爲user的對象,所以其值不確定,因此錯誤

相關問題