通过对话框组件执行 POST http 请求

To perform POST http request by an dialog component

我有一个名为 list 的组件,它将显示 api 中的一些标题名称,如下所示:

如图所示,我有 fab-button 调用 Add。单击此 fab-button。我正在调用一个对话框 window(组件名称是 add-customer)。像这样:

现在从这个对话框 window 我想填写表单的输入字段(即标题和描述)并且我想要 post 它服务器,意味着我想发送 http POST 点击请求 保存 按钮。

我可以使用 GET method.But 为 POST 方法调用 api,我我做不到。

DEMO

add-customer.ts 中,我将表单中的值传递给名为 postCustomer

的函数

我可以在控制台中看到:

我只想知道如何将此 postCustomer 函数分配给 service.ts 文件中的 POST 方法。

我正在尝试这样:

   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 而不是 Observables,您必须更改它们以获得更高的一致性和更强大的运算符。