首页 文章

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

提问于
浏览
0

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

如图所示,我有 fab-button 称为 Add . 点击这个fab-button . 我正在调用一个对话框窗口(组件名称是add-customer) . 像这样:

现在从这个对话框窗口我想填写表单的输入字段(i,e Headers 和描述),我想要发布它服务器,意味着我想要点击 SAVE 按钮发送 http POST 请求 .

我可以使用 GET 方法调用api . 但是对于 POST 方法,我无法做到 .

DEMO

add-customer.ts 我将值从表单传递给一个名为 postCustomer 的函数

我可以在控制台中看到:

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

我这样想:

public postCustomer(): Promise<IContact[]> {
    const apiUrl: string = 'api.........';

    return this.http.post<IContact[]>(apiUrl).toPromise();
  }

1 回答

  • 1

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

    NOTE: 我不明白为什么你在 Observables 上使用 Promises ,你必须改变它们以获得更多的一致性和强大的操作符 .

相关问题