问题
I have a simple Angular form which I want to post a Loan object to a .net core web API.
After submitting the form I can see this data in the console:
Object { Id: 0, BorrowerName: "asd", RepaymentAmount: 11.5, FundingAmount: 10 }
But my API action never gets called.
What am I doing wrong?
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>
回答1:
You are missing "subscription" for the post request.
this.http.post('http://localhost:1113/api/loans', this.model, config).subscribe();
回答2:
Anything with Observable should be subscribed to make your request works,
this.http.post('http://localhost:1113/api/loans', this.model, config).subscribe(data => {
console.log(data);
});
来源:https://stackoverflow.com/questions/53686113/httpclient-fails-to-post-to-web-api