首页 > 解决方案 > 通过对话框组件执行 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();
  }

标签: angularangular6angular-services

解决方案


对于 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) { }

注意:我不明白您为什么要使用Promisesover Observables,您必须更改它们以获得更一致和更强大的运算符。


推荐阅读