typescript 如何从Angular调用.NET Core API,它在其参数中接受模型?

cigdeys3  于 2023-05-19  发布在  TypeScript
关注(0)|答案(1)|浏览(123)

请帮助,我想从一个.NET核心API获取一个列表,我一直得到一个错误415,媒体类型不支持。
service.ts文件中,我有:

getProductList(listObj:any) {
    return this.http.get<any>(`${this.baseUrl}GetFilteredList`,listObj);
}

ts文件中的

products:any= [];

ngOnInit() {
    this.api.getProductList(this.products).subscribe({
      next:(res)=>{
        if(res.status){
          this.products = res.record;
        }
      }
    })

API以一个包含8个属性的模型作为参数

public ResultModel ProductList(ProductModel model) {
{
    "subCategoryID": 0,
    "categoryID": 0,
    "key 3" : ""
}

API调用返回

"status": true,
    "record": [
        {
            "key1": 0,
            "key 2": 62,
            "key 3" : "string val"
            .
            .

        },
        {
            "categoryID": 0,
            "saleListingID": 61,
            "key 3" : "string val"
        },

我想在component.html文件中显示res.record

<ul *ngFor="let product of products">
    <li> {{product.subCategoryID}} </li>
    <li> {{product.categoryID}} </li>
    <li> {{product.price}} </li>
    <li> {{product.country}} </li>
</ul>
oyxsuwqo

oyxsuwqo1#

如果你的http方法是Get,你可以在后端操作中添加[FromQuery]属性来绑定route的值,请参考这个简单的demo:

产品型号

public class ProductModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

API

[HttpGet]
public List<ResultModel> Get([FromQuery]ProductModel model)
{
      //........
        List<ResultModel> result = new List<ResultModel>()
        {
            new ResultModel()
            {
                subCategoryID = 1,
                categoryID = 1,
                price = 10, 
                country = "UK"
            },
            new ResultModel()
            {
                subCategoryID = 2,
                categoryID = 2,
                price = 20,
                country = "USA"
            },
            new ResultModel()
            {
                subCategoryID = 3,
                categoryID = 3,
                price = 46,
                country = "CN"
            }
        };

        return result;
}

**Angular **

let params = new HttpParams({ fromObject: {Id: "1", Name: "Jack",Age:"22"}})
    this.client.get('https://localhost:7273/api/Test',{params:params}).subscribe(console.log)

Gif Demo

从上面的Gif,后端绑定值成功。

相关问题