如何将 C# class 映射到 angular object

How map C# class to angular object

我有一个 object class,我想在我的 ASP.NET 核心 angular 项目中使用它。我无法通过 http get 方法映射 object return。请问有什么选择吗?

class 文件:

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

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

编辑:现在 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;
   }

'''

我有这个错误:

Object { headers: {...}, status: 404, statusText: "Not Found", url: "https://localhost:44374/api/UpdatePrices/PostUpdatePrices[object%20Object]", ok: false, name: "HttpErrorResponse", message: "Http failure response for https://localhost:44374/api/UpdatePrices/PostUpdatePrices[object%20Object]: 404 Not Found" ,错误:“\n\n\n\nError\n\n\n

Cannot POST /api/UpdatePrices/PostUpdatePrices%5Bobject%20Object%5D
\n\n\n”}

我假设你的 api return PricesRules 而不是 IEnumerable<PricesRules>(正如你所说的那样你得到了数据)。所以因为结果将是一个像 {Prices:[...],...} 所以你不能通过索引访问它你需要改变

this.prices = result[0];

this.prices = result.Prices;

this.prices = result['Prices'];

我修改了component.ts

'''

 const headers = new HttpHeaders()

      .set("Content-Type", "application/json");



  this.http.post(this.baseUrl + 'api/UpdatePrices/PostUpdatePrices',

      this.prices,

      { headers })

      .subscribe(

          val => {

              console.log("PUT call successful value returned in body",

                  val);

          },

          response => {

              console.log("PUT call in error", response);

          },

          () => {

              console.log("The PUT observable is now completed.");

          }

      );

'''