Tony
Tony

Reputation: 1264

Cannot read property 'name' of undefined Angular input-form

I'm using what I learned from Angular Tutorial to make a simple component. My component get data from angular-in-memory-web-api through service call UserService. Then I add input form to create new user. The error here when I click add button, the response from UserService cannot add new User(name, address) (Sorry if I wrong here) and therefore can't pass back data for html file. How can I fix it? any advice would be much appreciated.

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

Upvotes: 0

Views: 6938

Answers (1)

Vamshi
Vamshi

Reputation: 9351

You don't have a user object in your component . Create one before using it in form .

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

When you are using ngModel , that's two way data binding . So it tries to evaluate the initial value. In your case you gave user.name but there is no object named user , so its value is undefined , hence the error

Upvotes: 1

Related Questions