我有一个对象类,我想在我的 ASP.NET Core Angular 项目中使用它。我无法通过 http get 方法映射对象返回。有什么选择吗?
类文件:
[Serializable]
public class PricesRules
{
public HashSet<Price> Prices { get; set; }
public HashSet<Customer> Customers { get; set; }
public HashSet<Payment> Payments { get; set; }
}
component.ts :
public prices: PricesRules;
constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) {
http.get<PricesRules>(baseUrl + 'api/UpdatePrices/GetLastPrices').subscribe(result => {
this.prices = result[0];
}, error => console.error(error));
}
interface PricesRules {
Prices: any[];
Customers: any[];
Payments: any[];
}
Controller 文件:
[HttpGet("[action]")]
public IEnumerable<PricesRules> GetLastPrices()
{
PricesRules pricesRules = null;
//some code here
yield return pricesRules;
}
在我的组件中,我的结果对象中有很好的值,但之后我的对象价格未定义。
编辑:现在 get 方法没问题,但我的 post 方法没有触发我的 Controller 。
组件.ts '''
onClickSubmit(data) {
const params = new HttpParams().set('ID', '1');
const headers = new HttpHeaders().set('content-type', 'application/json');
this.http.post<PricesRules>(this.baseUrl + 'api/UpdatePrices/PostUpdatePrices' + this.prices, { headers, params }).subscribe(result => {
console.log("success");
}, error => console.error(error));
} '''
Controller
'''
[HttpPost("[action]")]
public async Task<IActionResult> PostUpdatePrices([FromBody] PricesRules pricesRules)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
return null;
}
'''
我有这个错误:
Object { headers: {…}, status: 404, statusText: "Not Found", url: "https://localhost:44374/api/UpdatePrices/PostUpdatePrices[object%20Object] ", ok: false, name: "HttpErrorResponse", message: "Http 失败响应 https://localhost:44374/api/UpdatePrices/PostUpdatePrices[object%20Object] : 404 Not Found", 错误: "\n\n\n\n错误\n\n\n
Cannot POST /api/UpdatePrices/PostUpdatePrices%5Bobject%20Object%5D\n\n\n"
最佳答案
我假设你的 api 返回 PricesRules
而不是 IEnumerable<PricesRules>
(正如你所说,你得到了数据)。所以因为结果将是一个像{Prices:[...],...}
这样的对象所以你不能通过索引访问它你需要改变
this.prices = result[0];
到
this.prices = result.Prices;
或this.prices = result['Prices'];
关于c# - 如何将 C# 类映射到 Angular 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58318027/