Когда я использую методы GET и POST на порте 4200, используя Postman, все работает нормально. Но в браузере, когда я отправляю форму, он показывает HttpErrorResponse {заголовки: HttpHeaders, status: 400, statusText: «Bad Request», url: «http://localhost:3000/employees/undefined", ok: false,…}
Здесь я включил только соответствующие части кода ...
model.ts
export class Employee {
_id: string;
name: string;
position: string;
office: string;
salary: number;
}
serivice.ts
export class EmployeeService {
selectedEmployee: Employee;
employees: Employee[];
readonly baseURL = 'http://localhost:3000/employees';
constructor( private http: HttpClient ) { }
postEmployee(emp: Employee): Observable<Employee> {
return this.http.post<Employee>(this.baseURL, emp);
}
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}`);
}
}
component.html
<form #employeeForm="ngForm" (ngSubmit)="onSubmit(employeeForm)">
<!-- _Id -->
<input type="hidden" name="_id" #_id="ngModel" [(ngModel)]="employeeService?.selectedEmployee._id">
<!-- name -->
<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>
<button class="btn btn-custom right" type="submit" [disabled]="!employeeForm.valid">Submit</button>
component.ts
export class EmployeeComponent implements OnInit {
constructor( public employeeService: EmployeeService) { }
ngOnInit() {
this.resetForm();
this.employeeService.selectedEmployee = new Employee ();
}
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' });
});
} else {
this.employeeService.putEmployee(form.value).subscribe((res) => {
this.resetForm(form);
this.refreshEmployeeList();
M.toast({ html: 'Updated successfully', classes: 'rounded' });
});
}
}