首页 文章

HttpClient无法发布到Web API

提问于
浏览
0

我有一个简单的Angular表单,我想将 Loan 对象发布到.net核心Web API .

提交表单后,我可以在控制台中看到这些数据:

对象{Id:0,BorrowerName:“asd”,RepaymentAmount:11.5,FundingAmount:10}

但我的API动作永远不会被调用 .

我究竟做错了什么?

Api Action

[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; }
}

loan-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);
  }
}

loan-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>

2 回答

  • 1

    您缺少发布请求的“订阅” .

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

    任何有Observable的东西都应该订阅以使你的请求有效,

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

相关问题