0

I have an api which will return the map response like .

{thomas: 3, test70: 2, tim: 2, elin: 2, sumeet12: 1}

I want to iterate in angular but unfortunately i got error while trying this.

Error Got ::

This expression is not callable. Type 'Number' has no call signatures.ts(2349)

  this.testObject.forEach((value: number, key: string) => {
    console.log(key, value);
});

Iterating over Typescript Map

But i am able to iterate in the html using below code..

In html

  <div *ngFor="let item of testObject | keyvalue: originalOrder; let i=index">
    <span *ngIf="i<3">
      Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>

    </span>   
  </div>

In .ts file

testObject: { [key: string]: number };
showresult: any;

  getQuizResult(id){
    this.service.getResult(id).subscribe((stndrdResp: Response) => {
      this.showresult = stndrdResp.obj; // this will return a object
      this.testObject = this.showresult; // assigning the key value response to testObject
      });
  }

Basically i want to iterate the backend api response inside the getQuizResult so that i can perform some action. Appreciate your valuable suggestion.

  • Have you checked: https://stackoverflow.com/questions/45605257/observable-with-angular-4-ngfor-only-supports-binding-to-iterables-such-as-arr ? – eko Apr 10 '20 at 07:54
  • @eko yes using this i am able to retrieve the keys but not the corresponding values. Could you please guide me how to get the corresponding value – Sumeet Kumar Tiwari Apr 10 '20 at 08:42

2 Answers2

0

I think this is what you are looking for: https://stackoverflow.com/a/24440475/12193298

A comment; in one of your code above you have key: string in the second parameter, but in the forEach callback the second one is the index, which always is a number. So that should be looking like this:

this.testObject.forEach((value: number, index: number) => {
    console.log(index, value);
});
Jeroenouw
  • 149
  • 1
  • 9
0

Because testObject is a plain object,not a Map instance.You need to create a map object or array.

const res = {thomas: 3, test70: 2, tim: 2, elin: 2, sumeet12: 1};
var arr = Object.entries(res);//[[ "thomas", 3 ]...]
var map = new Map(arr);//use arr or create a map
cyan
  • 209
  • 1
  • 3
  • 8