【发布时间】:2021-01-27 03:16:04
【问题描述】:
我正在尝试使用 MEAN 堆栈开发一个简单的 crud 应用程序,但是在尝试发布表单值时,角度服务没有发出发布请求。获取请求可以完美运行,但不能发布。我正在使用 morgan 查看对 nodejs 服务器发出的请求,但它没有接收到 post 请求,并且似乎与 angular 文档中的方式相同。我导入了 HttpClient 模块。
empleados.component.html
<form [formGroup]="nuevoEmpleado" (submit)="addEmpleado()">
<label>
Nombre:
<input type="text" formControlName="nombre">
</label>
<label>
Apellido:
<input type="text" formControlName="apellido">
</label>
<label>
Cargo:
<input type="text" formControlName="cargo">
</label>
<button class="btn btn-primary" type="submit">Agregar Nuevo Empleado</button>
</form>
{{ nuevoEmpleado.value | json }}
<div class="main-container">
<table class="table table-dark">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Nombre</th>
<th scope="col">Apellido</th>
<th scope="col">Cargo</th>
</tr>
</thead>
<tbody>
<tr *ngFor = "let empleado of listaEmpleados">
<th>{{ empleado.index }}</th>
<td>{{ empleado.nombre }}</td>
<td>{{ empleado.apellido}}</td>
<td>{{ empleado.cargo }}</td>
</tr>
</tbody>
</table>
</div>
empleados.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup , FormControl } from '@angular/forms';
import { EmpleadosService } from './empleados.service'
import { Empleado } from '../../clases/empleado'
@Component({
selector: 'app-empleados',
templateUrl: './empleados.component.html',
styleUrls: ['./empleados.component.css']
})
export class EmpleadosComponent implements OnInit {
listaEmpleados: Empleado[];
nuevoEmpleado = new FormGroup({
nombre: new FormControl(''),
apellido: new FormControl(''),
cargo: new FormControl('')
});
constructor(private empleadosService: EmpleadosService) { }
getEmpleados(){
this.empleadosService.getEmpleados().subscribe(empleados => this.listaEmpleados = empleados);
}
addEmpleado(){
this.empleadosService.addEmpleado(this.nuevoEmpleado.value);
}
ngOnInit(): void {
this.getEmpleados();
this.addEmpleado();
}
}
empleados.service.ts
import { Injectable } from '@angular/core';
import { HttpClient , HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Empleado } from '../../clases/empleado'
@Injectable({
providedIn: 'root'
})
export class EmpleadosService {
//url = 'assets/config.json'
url = 'http://localhost:3000'
constructor(private http: HttpClient) { }
getEmpleados():Observable<Empleado[]>{
return this.http.get<Empleado[]>(this.url);
}
addEmpleado(nuevoEmpleado: Empleado){
console.log(nuevoEmpleado);
return this.http.post<Empleado>(this.url , nuevoEmpleado)
}
}
【问题讨论】:
-
你需要
subscribepost call。 -
addEmpleado() 的结果是一个 Observable。查找 Observables 或 http.post 调用的示例!
-
比你,我订阅了,现在它正在工作