Angular response object being iterated through in a loop

I am facing a challenge while trying to iterate through an array containing values that need to be displayed to the user. Despite receiving a response with the data, I am having trouble accessing and looping through the elements of the array using Angular. I am unsure about what might be causing this issue.

Here is the C# code snippet:

 [EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
public class MapController : ApiController
{
    Map[] map = new Map[]
    {
        new Map { Map_Data_ID = 122, County = "West Yorkshire", Color = "#d45faa"},
        new Map { Map_Data_ID = 122, County = "West Yorkshire", Color = "#d45faa"},
    };

    public IEnumerable<Map> GetAllProducts()
    {
        return map;
    }
}

And here's the Angular code snippet:

test: Array<{id: Number, value: string, color: string}> = [];

getMapData() {     
       this._interactiveMapService.getMapData()
          .subscribe(
              data => {
                  var arr = Object.keys(data).map(key => ({type: key, value: data[key]}));
                  for(var i; i < arr.length; i++) {
                    this.test.push({id: i.Map_Data_ID, value: i.County, color: i.Color});
                  }
              })
    }

https://i.sstatic.net/JLdM7.png

I aim to integrate the received response data into the following structure:

For example:

 this.dataSource = {
      chart: {
        caption: "Depot Locations",
        subcaption: "United Kingdom (Counties)",
        numbersuffix: "%",
        includevalueinlabels: "1",
        labelsepchar: ": ",
        entityFillHoverColor: "#FFF000",
        theme: "fint",
      },   
      // Source data as JSON --> id represents counties of England.
      data: [
        {
          id: "126",
          value: "Anglesey",       
          color: "#d45faa"
        },
        {
          id: "108",
          value: "Argyl & Bute",          
          color: "#d45faa"
        }
      ]
    }

An example of the response from the server:

[
    {
        "Map_Data_ID": 122,
        "County": "West Yorkshire",
        "Color": "#d45faa"
    },
    {
        "Map_Data_ID": 167,
        "County": "Wiltshire",
        "Color": "#d45faa"
    }
]

Answer №1

Assuming the response is structured as follows:

data =  [ { "Map_Data_ID": 122, "County": "West Yorkshire", "Color": "#d45faa" }, { "Map_Data_ID": 167, "County": "Wiltshire", "Color": "#d45faa" } ];

You can achieve this by utilizing

.subscribe(data => {
  this.data.forEach(e => {
    this.test.push({
      id: e.Map_Data_ID,
      value: e.County,
      color: e.Color
    })
  })
});

Given that we are working in a typescript environment, it is beneficial to create a class for organizing this data.

export class CountryDetails {
  constructor(
    private id: number,
    private value: string,
    private color: string
  ) {}
}

Now, you can use the newly defined class like so:

.subscribe(data => {
  this.data.forEach(e => {
    this.test.push(new CountryDetails(e.Map_Data_ID, e.County, e.Color));
  })
});

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

Is it possible to utilize an await in an rxjs observable?

Implementing an interceptor for my HTTP requests requires the use of the access token from the user instance. Within my app component, I initialize the user: app.component.ts private async restoreUser(): Promise<UserModel | any> { // ... some vi ...

Implementing a post method in Angular without a request body

I've been attempting to send a JSON request and handle the response, but I keep encountering these errors: zone-evergreen.js:2952 OPTIONS http://'api':10050/api/content/Delivery net::ERR_EMPTY_RESPONSE core.js:6014 ERROR HttpErrorResponse ...

Hardware meets imagination. Crazy or genius?

The other day, I discovered a fascinating Verilog trick. Using a shift register to count the number of incrementations when something needs to be done repeatedly is quite clever. Simply shifting a 1 from the LSB to the MSB and once it reaches the MSB, the ...

Unable to access property 'scrollToBottom' as it is undefined

I'm encountering the error "Cannot read property 'scrollToBottom' of undefined" and haven't been able to find a solution anywhere, hence this post: Here is my use case: I have a custom accordion list, and on click of one of the list i ...

The function fromEvent is throwing an error stating that the property does not exist on the type 'Event'

I'm attempting to adjust the position of an element based on the cursor's location. Here is the code I am currently using: this.ngZone.runOutsideAngular(() => { fromEvent(window, 'mousemove').pipe( filter(() => this.hove ...

Error in unit testing: Trying to access property 'pipe' of an undefined variable results in a TypeError

Recently, I've been faced with the challenge of writing a unit test for one of the functions in my component. The specific function in question is called 'setup', which internally calls another function named 'additionalSetup'. In ...

What could be the reason behind the for loop not incrementing and the splice not being modified in my code?

Encountered a seemingly simple problem while coding, but the expected returns started deviating as I progressed. Your assistance would be greatly appreciated. If you do provide help, please elaborate on your approach and where I hit a roadblock. The Chal ...

An include action for a dynamic DbSet is failing to be implemented

I am currently working on implementing a method in my base repository that allows for dynamic includes. Let's consider the following example of what I am trying to achieve: public async Task<IList<Presentation>> All() { return await Db ...

Tips on making a forced call to `super.ngOnDestroy`

I am utilizing an abstract class to prevent redundant code for unsubscribing observables. Here is what it looks like: export abstract class SubscriptionManagmentDirective implements OnDestroy { componetDestroyed = new Subject<void>() constructor ...

issues arise when using array_merge, serialize, and unserialize functions in PHP

I am faced with the following task: Insert an associative array into a database field so that it can be reused as an associative array. [Completed using serialize($associativeArray)] Retrieve the associative array from the database and view it as an arra ...

Using Vue js and Typescript to automatically scroll to the bottom of a div whenever there are changes in

My goal is to automatically scroll to the bottom of a div whenever a new comment is added. Here's what I have been trying: gotoBottom() { let content = this.$refs.commentsWrapper; content.scrollTop = content.scrollHeight } The div containing ...

The Datagridview is unable to assign a null value to Column <ColumnName>

I am working with a DataGridView that is binding data from a DataTable, and one of the columns is named BOMOperationID. This column is populated based on the selected value of a Combobox. Everything is functioning correctly except when I select the first i ...

Enhancing Ionic's functionality by including extra access control to permit origin in response headers

Dealing with the issue of Ionic/Angular adding extra access control allow origin to response headers. How can this be prevented? My Nginx server currently has CORS enabled add_header 'Access-Control-Allow-Origin' '*' always; add_header ...

Choose to either push as a single object or as individual items

I have a quick question that I'd like to get some clarity on. Can someone explain the distinction between these two code snippets: export const addToCart = function(product, quantity){ cart.push({product, quantity}); console.log(`${quantity} ...

Learn how to access nested arrays within an array in React using TypeScript without having to manually specify the type of ID

interface UserInformation { id:number; question: string; updated_at: string; deleted_at: string; old_question_id: string; horizontal: number; type_id: number; solving_explanation:string; ...

What is the reason for the absence of an array length function in the C programming language?

Even though there are numerous methods to determine the length of an array in C, the language itself does not have a built-in function for this task. What could be the rationale behind omitting such a frequently used operation from C and its subsequent ve ...

Display the initial occurrence from the *ngIf statement

Is there a way to display only the first match from the *ngIf? I am currently using an object loop with *ngFor, where I have multiple items with the same Id but different dates. I need to filter and display only the item with the most recent date and avo ...

Using Sass variables within Angular2 components

In my project, I leverage Angular2 and angular-cli. Within the global style.scss file, I have defined several Sass variables. How can I retrieve these variables within my custom components (component.scss)? Should I perhaps import a separate file contain ...

Tips on transferring a child Interface to a parent class

Here is my code snippet: LocationController.ts import {GenericController} from './_genericController'; interface Response { id : number, code: string, name: string, type: string, long: number, lat: number } const fields ...

Forgot to include a semicolon in your code? If you attempted to parse SCSS using the regular CSS parser, give it another shot but this time with the

I am currently working on an Angular 14 project and one of my tasks involves changing the default font to our company's specific font. We are utilizing Angular material components and styles, so it is important for me to not only set the default font ...