Search code examples
angularjssymfony-3.3

ERROR TypeError: Cannot read property 'username' of undefined


I want to add user with angular js Frontend and symfony(Backend),i this error and my data in selector is emty .can someone know what's the problem

AddUserComponent.html:16 ERROR TypeError: Cannot read property 'username' of undefined at Object.eval [as updateRenderer] (AddUserComponent.html:20) at Object.debugUpdateRenderer [as updateRenderer] (core.es5.js:13105) at checkAndUpdateView (core.es5.js:12256) at callViewAction (core.es5.js:12599) at execComponentViewsAction (core.es5.js:12531) at checkAndUpdateView (core.es5.js:12257) at callViewAction (core.es5.js:12599) at execEmbeddedViewsAction (core.es5.js:12557) at checkAndUpdateView (core.es5.js:12252) at callViewAction (core.es5.js:12599) View_AddUserComponent_0 @ AddUserComponent.html:16 AddUserComponent.html:16 ERROR CONTEXT DebugContext_

add-user.component

Add User

  <div class="form-group">
    <label>username:</label>
    <input type="text" class="form-control" placeholder="add username" [(ngModel)]="usernamee" name="username" >
  </div>
  <div class="form-group">
    <label>Email:</label>
    <input type="text" class="form-control" placeholder="add email" [(ngModel)]="emaill" name="email" >
  </div>
<select>
  <option ng-repeat="user in users.result">{{user.username}}</option>
  </select>

      <div *ngFor="let error of errors" class="alert alert-danger">
          <div>There is an error in :{{error.field}} field</div>
          <div>{{error.message}}</div>
        </div>

  <button type="submit" class="btn btn-primary" >Save</button>

</form>

add-user.component

 import { Component, OnInit } from '@angular/core';
    import {UserService} from '../user.service';
    import {Router} from '@angular/router';

    @Component({
      selector: 'app-add-post',
      templateUrl: './add-user.component.html',
      styleUrls: ['./add-user.component.css']
    })
    export class AddUserComponent implements OnInit {

      username: string ;
      email: string;

      errors= [];


      constructor(private _userService: UserService , private router: Router) { }

      addUser(username, email) {

        let user: any;
        user = {username: username, email: email};
        this._userService.addUser(user).subscribe(( result => {

          this.router.navigate(['/users']);

        }), addError => this.errors = addError);

      }


  ngOnInit() {
  }

}

Userservice

addUser(user: User) {
        const  headers = new Headers();
        headers.append('content-type', 'application/json');
        headers.append('Authorization', 'Bearer ' + this.authenticationService.token);
        return this.http.post(this.uri, JSON.stringify(user), {headers : headers}).map(res => res.json()).catch(this.handelError);
      }

Solution

  • There is a typo in your HTML ngModel. change

    [(ngModel)]="usernamee"
    

    to

    [(ngModel)]="username"