angular - 如何根据 Angular 中 GET API 的响应调用 POST 和 PUT API?
问题描述
当我的组件被加载时,我需要检查我的 get api 响应。如果我得到get API
response == null
我需要使用相同的表格发布数据。当我的get API
response != null
,那么我需要将值修补到表单并且应该能够使用 PUT API 更新它
我尝试了以下方式并在尝试使用反应形式时卡住了。如果我有两个带有两个点击事件的按钮,我可以隐藏我的发布 api 按钮并显示更新 api 按钮以获取get API
请求(如果它具有价值)。类似的方式我可以显示发布请求 api 按钮,如果get API
reqresponse == null
html
<form (ngSubmit)="onRegisterSubmit(form)" [formGroup] = "form">
<input type="text" formControlName="username" class="form-control" >
<input type="submit" class="btn btn-primary" value="Submit" [disabled]="!form.valid">
</form>
更新
username;
getResponse
Constructor() {
this.getVal()
}
getVal() {
http.get<any>(API).subscribe(response => {
this.getResponse= response;
if (this.getResponse != null) {
this.form.patchValue({. //append the values to the form
username: response.username,
})
})
}
onRegisterSubmit(form) {
this.username = form.value
console.log(form.value);
if (this.getResponse != null) {
//I want to enable update button and update api here
return http.put<any>(api, this.username).subscribe(resposne =>
console.log(response) )
} if(response == null) {
return http.post<any>(api, this.username).subscribe(resposne =>
console.log(response) )
//I want to send data using post method.
}
}
解决方案
推荐阅读
- java - USB 设备在打开应用程序后重新连接后才能使用
- mysql - 查询中的多个左连接返回不正确的计数
- python-3.x - 从 azure.storage.blob 导入 BlockBlobService 不起作用
- c# - 删除最后一个逗号和 CsvHelper 将第一行附加到标题
- excel - sumproduct 中动态范围的外部链接
- ember.js - 如何在 ember Qunit 测试中覆盖集成测试中的组件功能
- highcharts - 在 HighStock 中鼠标悬停绘制另一个图表/或系列
- nginx - ./configure: 错误:HTTP XSLT 模块需要 libxml2/libxslt 库
- mysql - 如何将多个值的总和相加
- r - 使用可下载的 pdf 文档发布闪亮的应用程序