HttpClient的失败张贴到网络API(HttpClient fails to post to

2019-10-28 12:50发布

我有我想要一个发布一个简单的角形式Loan对象为.NET核心Web API。

提交表格后,我可以在控制台中看到这样的数据:

对象{ID:0,BorrowerName: “ASD”,RepaymentAmount:11.5,FundingAmount:10}

但是我的API的行动不会被调用。

我究竟做错了什么?

API动作

[HttpGet]
public ActionResult<IEnumerable<Loan>> Get()
{
    return _context.Loans;
}

Loan.cs

public class Loan
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string BorrowerName { get; set; }
    public decimal RepaymentAmount { get; set; }
    public decimal FundingAmount { get; set; }
}

贷款form.component.ts

import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { Loan } from '../loan';

@Component({
  selector: 'app-loan-form',
  templateUrl: './loan-form.component.html',
  styleUrls: ['./loan-form.component.css']
})

export class LoanFormComponent implements OnInit {

  model = new Loan(0, "", 0, 0);

  constructor(private http:HttpClient) {  }

  ngOnInit() {
  }

  setRepaymentAmount(event) {
    this.model.RepaymentAmount = event * 1.15;
  } 
  onSubmit() {
    console.log(this.model);
    var config = {
      headers : {
          'Content-Type': 'application/json;charset=utf-8;'
      }
    }
    this.http.post('http://localhost:1113/api/loans', this.model, config);
  }
}

贷款form.component.html

<div class="container">

  <h1>New Loan Form</h1>

  <form (ngSubmit)="onSubmit()" #loanForm="ngForm">
    <div class="form-group">
      <label for="BorrowerName">Borrower Name</label>
      <input type="text" 
            class="form-control" 
            id="BorrowerName" 
            required
            [(ngModel)]="model.BorrowerName" name="BorrowerName"
            #spy>
    </div>

    <div class="form-group">
      <label for="FundingAmount">Funding Amount</label>

        <input type="number" class="form-control" id="FundingAmount" required
          [(ngModel)]="model.FundingAmount" name="FundingAmount"
          (ngModelChange)="setRepaymentAmount($event)"
          #spy>
    </div>

    <div class="form-group">
      <label for="RepaymentAmount">Repayment Amount</label>
      <input type="number" class="form-control" id="RepaymentAmount"
      [(ngModel)]="model.RepaymentAmount" name="RepaymentAmount" readonly>
      TODO: remove this: {{model.RepaymentAmount}}
    </div>

    <button type="submit" class="btn btn-success" [disabled]="!loanForm.form.valid">Submit</button>

  </form>
</div>

Answer 1:

这是因为丢失“订阅”的职位要求。

this.http.post('http://localhost:1113/api/loans', this.model, config).subscribe();


Answer 2:

以可观察到任何应订阅到提出请求的作品,

this.http.post('http://localhost:1113/api/loans', this.model, config).subscribe(data => {
  console.log(data);
});


文章来源: HttpClient fails to post to web API