如何将C#类映射到角对象

问题描述 投票:2回答:1

我有一个对象类,我想在我的ASP.NET Core角度项目中使用它。我无法通过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[];
}

控制器文件:

[HttpGet("[action]")]
public IEnumerable<PricesRules> GetLastPrices()
{
    PricesRules pricesRules = null;
    //some code here
    yield return pricesRules;
}

在我的组件中,结果对象具有良好的价值,但之后我的对象价格未定义。

编辑:现在,get方法可以,但是我的post方法没有触发我的控制器。

component.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));

}'''

控制器

'''

[HttpPost("[action]")]
    public async Task<IActionResult> PostUpdatePrices([FromBody] PricesRules pricesRules)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        return null;
   }

'''

我有此错误:

对象{标头:{…},状态:404,statusText:“未找到”,url:“ https://localhost:44374/api/UpdatePrices/PostUpdatePrices[object%20Object]”,确定:否,名称:“ HttpErrorResponse”,消息:“ https://localhost:44374/api/UpdatePrices/PostUpdatePrices[object%20Object]的Http失败响应:找不到404”,错误:“ \ n \ n \ n \ nError \ n \ n \ n

无法发布/ api / UpdatePrices / PostUpdatePrices%5Bobject%20Object%5D
\ n \ n \ n“}
c# angular asp.net-core mapping http-get
1个回答
0
投票

[我假设您的api返回PricesRules而不是IEnumerable<PricesRules>(就像您说的那样获取数据)。因此,由于结果将是一个像{Prices:[...],...}的对象,因此您无法通过索引访问它,因此需要进行更改] >

this.prices = result[0];

this.prices = result.Prices;

this.prices = result['Prices'];

© www.soinside.com 2019 - 2024. All rights reserved.