NgModel在Angular 5中无法正常工作

时间:2018-06-01 06:23:48

标签: angular

我有这样的问题。我正在使用angular 5,Nodejs和MongoDB创建一个Web应用程序。为了将数据发送到数据库,我创建了一个像这样的HTML文件。

<div class="row">
  <div class="col s12 m6">
    <div class="card blue-grey darken-1">
      <div class="card-content white-text">
        <div class="row">
          <div class="col s5">
            <form #employeeForm="ngForm" (ngSubmit)="onSubmit(employeeForm)">
              <input type="hidden" name="_id" #_id="ngModel" [(ngModel)]="employeeService.selectedEmployee._id">
              <div class="row">
                <div class="input-field col s12">
                  <input type="text" name="name" #name="ngModel" [(ngModel)]="employeeService.selectedEmployee.name" placeholder="Enter full name" required>
                  <label>Name :
                    <label class="red-text">*</label>
                  </label>
                </div>
              </div>
              <div class="row">
                <div class="input-field col s12">
                  <input type="text" name="position" #name="ngModel" [(ngModel)]="employeeService.selectedEmployee.position" placeholder="Eg : Snr. Developer">
                  <label>Position :</label>
                </div>
              </div>
              <div class="row">
                <div class="input-field col s12">
                  <input type="text" name="office" #name="ngModel" [(ngModel)]="employeeService.selectedEmployee.office" placeholder="Enter office location">
                  <label>Office :</label>
                </div>
              </div>
              <div class="row">
                <div class="input-field col s12">
                  <input type="text" name="salary" #name="ngModel" [(ngModel)]="employeeService.selectedEmployee.salary" placeholder="Salary per annum">
                  <label>Salary :</label>
                </div>
              </div>
              <div class="row">
                <div class="input-field col s12">
                  <button class="btn btn-custom right" type="button" (click)="resetForm(employeeForm)">Reset</button>
                  <button class="btn btn-custom right" type="submit" [disabled]="!employeeForm.valid">Submit</button>
                </div>
              </div>
            </form>
          </div>
          <div class="col s7">

          </div>
        </div>
      </div>
    </div>
  </div>
</div>

要将数据发送到后端,我在components.ts文件中创建了这样的方法。这是该文件中的代码。

import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';

import { EmployeeService } from '../shared/employee.service';
import { Employee } from '../shared/employee';

declare var M: any;

@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css'],
  providers: [EmployeeService]
})
export class EmployeeComponent implements OnInit {

  constructor(private employeeService: EmployeeService) { }

  ngOnInit() {
    this.resetForm();
    this.refreshEmployeeList();
  }
  resetForm(form?: NgForm) {
    if (form) {
      form.reset();
      this.employeeService.selectedEmployee = {
        _id: '',
        name: '',
        position: '',
        office: '',
        salary: null
      };
    }
  }

  onSubmit(form: NgForm) {
    if (form.value._id === '') {
      this.employeeService.postEmployee(form.value).subscribe((res) => {
        this.resetForm(form);
        M.toast({ html: 'Saved successfully', classes: 'rounded' });
      });
    }
  }

  refreshEmployeeList() {
    this.employeeService.getEmployeeList().subscribe( (res) => {
      this.employeeService.employees = res as Employee[];
    });
  }

  onEdit(emp: Employee) {
    this.employeeService.selectedEmployee = emp;
  }

  onDelete(_id: string, form: NgForm) {
    if (confirm('Are you sure to delete this record ?') === true) {
      this.employeeService.deleteEmployee(_id).subscribe((res) => {
        this.refreshEmployeeList();
        this.resetForm(form);
        M.toast({ html: 'Deleted successfully', classes: 'rounded' });
      });
    }
  }
}

我的服务文件是这样的。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

import { Employee } from './employee';

@Injectable()
export class EmployeeService {
  selectedEmployee: Employee;
  public  employees: Employee[];
  readonly baseURL = 'http://localhost:3000/employees';

  constructor(private http: HttpClient) { }

  postEmployee(employee: Employee) {
    return this.http.post(this.baseURL, employee);
  }

  getEmployeeList() {
    return this.http.get(this.baseURL);
  }

  putEmployee(emp: Employee) {
    return this.http.put(this.baseURL + `/${emp._id}`, emp);
  }

  deleteEmployee(_id: string) {
    return this.http.delete(this.baseURL + `/${_id}`);
  }

}

我的app.module.ts文件是这样的。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { EmployeeComponent } from './employee/employee.component';


@NgModule({
  declarations: [
    AppComponent,
    EmployeeComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

我的员工模型类看起来像这样。

export class Employee {
  public _id: string;
  public name: string;
  public position: string;
  public office: string;
  public salary: number;
}

当我点击服务时,它会给我一个这样的错误。

ERROR TypeError: Cannot read property '_id' of undefined
    at Object.eval [as updateDirectives] (EmployeeComponent.html:8)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:14697)
    at checkAndUpdateView (core.js:13844)
    at callViewAction (core.js:14195)
    at execComponentViewsAction (core.js:14127)
    at checkAndUpdateView (core.js:13850)
    at callViewAction (core.js:14195)
    at execComponentViewsAction (core.js:14127)
    at checkAndUpdateView (core.js:13850)
    at callWithDebugContext (core.js:15098)

昨天我也问过这个问题,我认为我的解释并不清楚。所以今天我要问的是更多的描述。有人可以帮我解决这个问题吗?非常感谢你。

2 个答案:

答案 0 :(得分:1)

试试这个,虽然它会推广你的对象,但它会起作用:

在您的EmployeeService中,声明selectedEmployee如下

selectedEmployee: any = {};

答案 1 :(得分:0)

我希望这会有所帮助,但是打字稿仍然会转换为javascript,这真的无法知道currentemployee是一个类,这就是为什么它说它无法找到我的字段。但是,您可以分配具有I字段的对象,但我没有看到发生这种情况的任何地方。我认为角度绑定不起作用,因为你只声明了,但没有初始化对象。

也许分配员工..

public currentEmployee : Employee = new Employee();

请原谅任何错误,只是一个大致的想法,在凌晨3点在我的床上打字无法入睡。