Tips for cycling through the backend API map reaction in Angular or Typescript

When I make a call to an API, it returns a response in the form of a map:

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

I tried iterating over this response in Angular, but encountered an error.

Error Encountered:

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

However, I found that I was able to iterate over the response in HTML using the following 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 the .ts file:

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

getQuizResult(id){
  this.service.getResult(id).subscribe((stndrdResp: Response) => {
    this.showresult = stndrdResp.obj;
    this.testObject = this.showresult;
  });
}

My main goal is to iterate over the backend API response within the getQuizResult function so that I can perform certain actions based on the data. Any suggestions would be greatly appreciated.

Answer №1

Here is the solution you've been searching for:

Just a quick note on your code snippet. In the example you provided, you have specified key: string in the second parameter, but within the forEach callback, the second parameter should actually be index, which will always be a number. Therefore, your code should look like this:

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

Answer №2

Since testObject is simply a regular object and not a Map instance, you will need to convert it into a map object or an array.

const data = {alice: 3, bob: 2, charlie: 1};
var objArray = Object.entries(data); //[[ "alice", 3 ]...]
var mapInstance = new Map(objArray); //use objArray or create a map

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating the parent component upon navigating from the child component in Angular app

Struggling with updating the parent component after routing from a child component. Through research, I've learned that ngOnInit only runs once. Any way to work around this issue? I've experimented with different lifecycle hooks, but no luck so f ...

Header remains fixed when scrolling

Is there a way to make the header of a Bootstrap table fixed when scrolling, while also adjusting the width of each column based on the content within it? I want the column headers to match the width of the row with the most text. Setting the position of t ...

Tips for restricting additional input when maximum length is reached in an Angular app

In my Angular 6 application, I am working on implementing a directive that prevents users from typing additional characters in an input field. However, I want to allow certain non-data input keys such as tab, delete, and backspace. Currently, I have an if ...

Modifying the Iterator Signature

My goal is to simplify handling two-dimensional arrays by creating a wrapper on the Array object. Although the code works, I encountered an issue with TypeScript complaining about the iterator signature not matching what Arrays should have. The desired fu ...

Exploring the power of Next.js, Styled-components, and leveraging Yandex Metrica Session Replay

I'm currently involved in a project that utilizes Next.js and styled-components. In my [slug].tsx file: export default function ProductDetails({ product }: IProductDetailsProps) { const router = useRouter(); if (router.isFallback) { return ( ...

Setting the useState hook to a User type in React - the ultimate guide!

As someone new to hooks, I'm unsure about what the initial value for useState should be set to. Currently, an empty object is set as the default value for useState with const [user, setUser] = useState({}); This is causing ${crafter.id} to throw an e ...

What is the process for implementing a decorator pattern using typescript?

I'm on a quest to dynamically create instances of various classes without the need to explicitly define each one. My ultimate goal is to implement the decorator pattern, but I've hit a roadblock in TypeScript due to compilation limitations. Desp ...

Failure to Apply Angular Conditional Class

What is the reason for test-abc not being included? <div class="abc" [class.test-abc]="true"></div> I successfully implemented it with this syntax: [ngClass]="{'foo': true, 'abc': true}" ...

What is the best way to extract data from API console output using Angular?

Currently, I am deeply involved in a full stack project utilizing asp.net and angularjs. My goal is to extract output response from the Swagger API. You can view the code I've written for this purpose here: (https://i.stack.imgur.com/vLyIE.png) The A ...

What steps need to be taken in VSCode to import React using IntelliSense?

When I press Enter in that image, nothing seems to occur. I believed IntelliSense would automatically insert import React from 'react'; at the beginning of the file. https://i.stack.imgur.com/7HxAf.png ...

What is the correct data type for the vuex store that is passed to the vuex plugin when it is being initialized?

Here is how the store initialization process is currently being implemented: /* Logic */ import Vue from 'vue' import Vuex, { StoreOptions } from 'vuex' Vue.use(Vuex) const DataManager = new UserDataManager() type RootStateType = { ...

Creating dynamic key objects in TypeScript with index signatures: A beginner's guide

How can the code be optimized to automatically initialize a new product type without adding extra lines of code? Failure to initialize the variable results in a syntax error. enum ProductType { PC = 'pc', LAPTOP = 'laptop', TV ...

Utilizing Angular 2 to pass parameters in an HTTP GET request

How can I include parameters in a GET request using Angular 2? I attempted the following method, but received an error message: Argument of type '{ params: URLSearchParams; }' is not assignable to parameter of type 'RequestOptionsArgs' ...

Angular: Understanding Render Delay Caused by *ngIf and Expression Changes from Filters

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf: true'. Encountering the above error in the console. In my code, I have filters that control ...

The attempt to register a ServiceWorker for the angular scope was unsuccessful

I have encountered various solutions to this issue, some of which are not suitable for Angular and others simply do not work. In my quest to implement the "add to Homescreen" feature, I came across a helpful blog post (https://blog.betapage.co/how-to-add ...

Compiling Typescript with union types containing singleton types results in errors

I'm having trouble understanding why the code below won't compile: type X = { id: "primary" inverted?: boolean } | { id: "secondary" inverted?: boolean } | { id: "tertiary" inverted?: false } const a = true const x: X = { id: a ? ...

Struggling with setting up a search bar for infinite scrolling content

After dedicating a significant amount of time to solving the puzzle of integrating infinite scroll with a search bar in Angular, I encountered an issue. I am currently using Angular 9 and ngx-infinite-scroll for achieving infinity scrolling functionality. ...

Encountering a 500 error (Internal Server Error) while trying to connect API Laravel 5.4 with Angular 2

Every time I try to submit a form from an Angular form to my API built on Laravel, I encounter a 500 error (Internal Server Error) in the console. What could be causing this issue? Note: The backend API functions perfectly when tested with POSTMAN. This ...

Integrating Constant Contact API into a Next.js application

I'm trying to integrate the Constant Contact API into my Next.js application. I've looked through the documentation, but it only provides examples for PHP and Java. How can I effectively use the authentication flow and create an app on the dashbo ...

When navigating to a new URL in Angular 7, the browser will automatically redirect to the home component

Currently, I'm developing a project using Angular 7.2.0. One issue I'm facing is that when I attempt to navigate to a particular page initially, such as: http://localhost:4200/comics?sort=series The browser always gets redirected to the root: ...