最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pass C# dictionary into typescript Map - Stack Overflow

programmeradmin9浏览0评论

How can I pass correctly C# dictionary into 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:

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: 20, 2: 30, 3: 40, 4: 50, 5: 70, 6: 60, 7: 90, 8: 30}

2

ERROR TypeError: this.reportsUsage.values is not a function

3

object

So the data type change from Dictionary into object, I have tried to convert it with the below but still not working:

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

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

How can I pass correctly C# dictionary into 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:

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: 20, 2: 30, 3: 40, 4: 50, 5: 70, 6: 60, 7: 90, 8: 30}

2

ERROR TypeError: this.reportsUsage.values is not a function

3

object

So the data type change from Dictionary into object, I have tried to convert it with the below but still not working:

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

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

Share Improve this question asked Jun 3, 2021 at 13:53 WhistlerWhistler 1,9776 gold badges31 silver badges51 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

I don't know that C# is very relevant here, other than the fact that what es over the wire is a JSON object like this:

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. 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".

So when you call your http.get you should specify Record<number, number> instead of 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. And since JSON objects always have string keys and not actual numbers, you need to convert to numbers yourself if you want the resulting map to be Map<number, number> instead of 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.

Let's make sure it works:

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

Looks good. Playground link to code

1- if you want to create a map out of reportsUsage:

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:

const arrayOfValues = Object.values(this.reportsUsage)
发布评论

评论列表(0)

  1. 暂无评论