简体   繁体   English

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

[英]How to pass C# dictionary into typescript Map

How can I pass correctly C# dictionary into typescript Map.如何正确地将 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 );
    }

In angular:在 angular 中:

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

Results:结果:

1 1

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

2 2

ERROR TypeError: this.reportsUsage.values is not a function错误类型错误:this.reportsUsage.values 不是 function

3 3

object object

So the data type change from Dictionary into object, I have tried to convert it with the below but still not working:因此数据类型从 Dictionary 更改为 object,我尝试使用以下内容进行转换,但仍然无法正常工作:

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

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

I don't know that C# is very relevant here, other than the fact that what comes over the wire is a JSON object like this:我不知道 C# 在这里非常相关,除了电线上出现的是 JSON object 这样的事实:

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

This is not already a JavaScript Map , but a plain JSON object.这还不是JavaScript Map ,而是普通的 JSON ZA8CFDE6331BD54B66AC96F8911C。 So the right type to use is probably Record<number, number> where I'm using the Record utility type to say "an object with numeric keys and numeric values".所以要使用的正确类型可能是Record<number, number>我使用Record实用程序类型说“带有数字键和数值的 object”。

So when you call your http.get you should specify Record<number, number> instead of Map<number, number> :因此,当您调用http.get时,您应该指定Record<number, number>而不是Map<number, number>

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

If you want to convert that into a Map , you need to call the Map constructor with an appropriately iterable argument (such as an array) of key-value tuples .如果要将其转换为Map ,则需要使用键值元组的适当可迭代参数(例如数组)调用Map构造函数 And since JSON objects always have string keys and not actual number s, you need to convert to numbers yourself if you want the resulting map to be Map<number, number> instead of Map<string, number> :并且由于 JSON 对象始终具有string键而不是实际number ,因此如果您希望生成的 map 为Map<number, number>而不是Map<string, number>则需要自己转换为数字:

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

This is using Object.entries() to convert the JavaScript object into an array of such entry tuples, and we are mapping these entries so that the keys are numbers.这是使用Object.entries()将 JavaScript object 转换为此类条目元组的数组,我们将这些条目映射为键。

Let's make sure it works:让我们确保它有效:

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

Looks good.看起来不错。 Playground link to code Playground 代码链接

1- if you want to create a map out of reportsUsage: 1-如果你想从reportsUsage中创建一个map:

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

2- if you want an array with the values only: 2-如果您想要一个仅包含值的数组:

const arrayOfValues = Object.values(this.reportsUsage)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM