angular - 通过对话框组件执行 POST http 请求
问题描述
我调用了一个组件list
,它将显示来自api的一些标题名称,如下所示:
如图所示,我fab-button
调用了Add。单击此工厂按钮。我正在调用一个对话窗口(组件名称是 add-customer)。像这样:
现在从这个对话框窗口我想填写表单的输入字段(即标题和描述),我想将它发布到服务器,意味着我想http POST
在单击
SAVE按钮时发送请求。
我可以使用GET方法调用 api。但是对于POST方法,我无法做到。
在add-customer.ts
我将表单中的值传递给一个名为postCustomer的函数
我可以在控制台中看到:
我只想知道如何将这个postCustomer函数分配给文件中的 POST 方法service.ts
。
我正在尝试这样:
public postCustomer(): Promise<IContact[]> {
const apiUrl: string = 'api.........';
return this.http.post<IContact[]>(apiUrl).toPromise();
}
解决方案
对于 POST 方法:
对于POST
您要发送正文的方法,请将您的服务更改为:
public postCustomer(data): Promise<IContact[]> {
const apiUrl: string = 'https://jsonplaceholder.typicode.com/posts';
return this.http.post<IContact[]>(apiUrl, data).toPromise();
}
然后在您的AddCustomerComponent
重构方法onAddCustomer()
中:
public onAddCustomer(): void {
this.markAsDirty(this.addCusForm);
this.postCustomer=this.addCusForm.value;
console.log(this.postCustomer);
this.service.postCustomer(this.postCustomer).then(
(response)=> {
console.log('POST called', response);
}
)
}
不要忘记Service
在同一个组件中导入您的:
import {Service} from '../service';
并将其注入constructor
:
constructor(private fb: FormBuilder, private service: Service) { }
注意:我不明白您为什么要使用Promises
over Observables
,您必须更改它们以获得更一致和更强大的运算符。
推荐阅读
- python - NameError: name 'spark' is not defined,如何解决?
- javascript - MERN 无法部署到 heroku
- kotlin - Kotlin ConflatedBroadcastChannel.offer() 不起作用?
- python - 出现问题时继续扫描另一个站点
- python-3.x - Bert 预训练模型每次给出随机输出
- javascript - 我想在滚动时显示 div 获取 TypeError: $ is not a function?
- javascript - Greasemonkey:如何删除随机 url 部分?
- ios - 单元格中有阴影的 TableView
- vb.net - 在按钮上调用函数/子单击 vb.net
- elasticsearch - ngram 匹配对不太相关的文档给出相同的分数