【问题标题】:How to pass C# dictionary into typescript Map如何将 C# 字典传递到 typescript Map
【发布时间】:2021-08-21 15:43:31
【问题描述】:

如何将 C# 字典正确传递到 typescript Map。

[HttpGet("reportsUsage")]
    public IActionResult GetReportsUsage()
    {
        //var reportsUsage = _statService.GetReportsUsage();

        IDictionary<int, int> test = new Dictionary<int, int>();

        test.Add(1, 20);
        test.Add(2, 30);
        test.Add(3, 40);
        test.Add(4, 50);
        test.Add(5, 70);
        test.Add(6, 60);
        test.Add(7, 90);
        test.Add(8, 30);

        return Ok(test);
        //return Ok(reportsUsage );
    }

角度:

getReportsUsage() {
return this.http.get<Map<number, number>>(`${environment.apiUrl}/stats/reportsUsage`, {
  headers: new HttpHeaders({
    'Content-Type': 'text/plain',
    'Accept': 'application/json'
  }),
  withCredentials: true
});
}

reportsUsage = new Map<number, number>();

this.statsService.getReportsUsage().subscribe(data => {
    this.reportsUsage = data;
    
    //1
    console.log(this.reportsUsage);
    //2
    console.log(this.reportsUsage.values());
    //3
    console.log(typeof(this.reportsUsage));
};

结果:

1

{1:20、2:30、3:40、4:50、5:70、6:60、7:90、8:30}

2

ERROR TypeError: this.reportsUsage.values 不是函数

3

对象

所以数据类型从字典变成了对象,我尝试用下面的方法转换它,但还是不行:

console.log(new Map(this.reportsUsage));

TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))

【问题讨论】:

    标签: javascript angular typescript asp.net-core asp.net-web-api


    【解决方案1】:

    我不知道 C# 在这里非常相关,除了通过网络传输的是这样的 JSON 对象这一事实:

    const data: Record<number, number> = 
      { 1: 20, 2: 30, 3: 40, 4: 50, 5: 70, 6: 60, 7: 90, 8: 30 };
    

    这已经不是JavaScript Map,而是一个普通的 JSON 对象。所以正确使用的类型可能是Record&lt;number, number&gt;,我使用Record utility type 表示“具有数字键和数值的对象”。

    因此,当您调用 http.get 时,您应该指定 Record&lt;number, number&gt; 而不是 Map&lt;number, number&gt;

    this.http.get<Record<number, number>>(...)
    

    如果要将其转换为Map,则需要使用键值tuples 的适当可迭代参数(例如数组)调用the Map constructor。由于 JSON 对象总是有 string 键而不是实际的 numbers,如果您希望结果映射为 Map&lt;number, number&gt; 而不是 Map&lt;string, number&gt;,则需要自己转换为数字:

    const map = new Map(Object.entries(data).map(([k, v]) => [+k, v]));
    // const map: Map<number, number>
    

    这是使用 Object.entries() 将 JavaScript 对象转换为此类条目元组的数组,我们是 mapping 这些条目,因此键是数字。

    让我们确保它有效:

    console.log(map.get(3)?.toFixed(2)) // "40.00"
    

    看起来不错。 Playground link to code

    【讨论】:

      【解决方案2】:

      1- 如果您想根据报告使用情况创建地图:

      const map = new Map(Object.entries(this.reportsUsage));
      console.log(map.get("1")); // prints 20
      

      2- 如果您想要一个仅包含值的数组:

      const arrayOfValues = Object.values(this.reportsUsage)
      

      【讨论】:

        猜你喜欢
        • 2023-03-24
        • 1970-01-01
        • 1970-01-01
        • 2018-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-02
        • 1970-01-01
        相关资源
        最近更新 更多