c# - 如何将 C# 类映射到 Angular 对象

标签 c# angular asp.net-core mapping http-get

我有一个对象类,我想在我的 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/

相关文章:

javascript - CKEditor 5 通过外部 url 插入图像

c# - 如何阻止日期时间验证器填充?

angular - ng : 'mat-table'  is not a known element

angular - Observable:如果在 map() 之前,为什么不导致 subscribe() 成功函数?

angular - 如何将额外的参数传递给 Angular 中的异步验证器(响应式(Reactive)表单)?

Asp.net Boilerplate - 没有给出与所需的形式参数相对应的参数

javascript - 如何从响应中读取文件名-reactJs

c# - Winform自定义控件为什么是 "Object Reference not set to an instance of an object"?

c#.net COM dll 中断了对 vb6 应用程序的引用

c# - 在不破坏字段的情况下设置 Range.Text?