首页 > 解决方案 > 如何根据 Angular 中 GET API 的响应调用 POST 和 PUT API?

问题描述

当我的组件被加载时,我需要检查我的 get api 响应。如果我得到get API response == null我需要使用相同的表格发布数据。当我的get API response != null,那么我需要将值修补到表单并且应该能够使用 PUT API 更新它

我尝试了以下方式并在尝试使用反应形式时卡住了。如果我有两个带有两个点击事件的按钮,我可以隐藏我的发布 api 按钮并显示更新 api 按钮以获取get API请求(如果它具有价值)。类似的方式我可以显示发布请求 api 按钮,如果get APIreqresponse == 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.
        }
 }

标签: angulartypescript

解决方案


推荐阅读