Transitioning from Angular Http to HttpClient: Overcoming Conversion Challenges

Currently, I am in the process of converting my old Angular app from Http to HttpClient. While working on the service.ts section, I encountered an error that I am struggling to resolve:

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

component.ts

import { Component, OnInit } from "@angular/core";
import { Rider } from "../interfaces/rider";
import { SpeedwayService } from "../../speedway.service";
import { OrderPipe } from "ngx-order-pipe";

@Component({
  selector: "gs-pgee2020",
  templateUrl: "./pgee2020.component.html",
  styleUrls: ["./pgee2020.component.less"]
})
export class Pgee2020Component {
  pgee2020: Array<any>;
  order: string = "MSC";
  reverse: boolean = false;
  result: number[];
  constructor(
    private _speedwayService: SpeedwayService,
    private orderPipe: OrderPipe
  ) {
    this._speedwayService.getPgee2020().subscribe(response => {
      this.pgee2020 = orderPipe.transform(response, "MSC");
    });
  }

  setOrder(value: string) {
    if (this.order === value) {
      this.reverse = !this.reverse;
    }
    this.order = value;
  }
}

service.ts (old, worked with Http)

getPgee2020() {
    return this._http
      .get("http://node.gurustats.usermd.net:60519/pgee2020")
      .map(result => (this.result = result.json().data));
  }

service.ts (new, not working with HttpClient)

getPgee2020() {
    return this._http
      .get("http://node.gurustats.usermd.net:60519/pgee2020").pipe(map((result => (this.result = result))));
    }

data structure

{
  "status": 200,
  "message": null,
  "data": [
    {
      "_id": "604a882ed87fdb0482536fc9",
      "MSC": 3,
      "ZAWODNIK": "Bartosz Zmarzlik",
      "KLUB": "Gorzów",
      "SREDNIA": 2.43,

component.html

 <tr
            *ngFor="
              let rider of pgee2020 | orderBy: order:reverse;
              let i = index" class="row-zaw"
            [routerLink]="[rider.id]">
          
            <td>{{ rider.MSC }}</td>
            <td>{{ rider.ZAWODNIK }}</td>
            <td>{{ rider.KLUB }}</td>
...

Answer №1

It appears that in order to fix the issue with your template breaking, you should iterate over the data property of pgee2020, rather than looping through the entire object itself. The reason for the breakage is because the latter is an object and cannot be iterated over with the current code.

To resolve this, please implement the following change:

<tr *ngFor="let item of pgee2020.data"> 
   .... 
</tr>

Answer №2

After encountering an obstacle, I was able to overcome it by making a modification in the service.ts file. While Nicholas provided a solution for Angular 5, I discovered my expertise lies in assisting with issues related to Angular 11.

  fetchPgeeData() {
    return this._http
      .get("http://node.gurustats.usermd.net:60519/pgee2020").pipe(map(res => res ['data']))

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

The ngx-translate library could not be located within Ionic Framework 6

Currently, I am looking to incorporate the ngx-translate Pipe for translating my Ionic application. In my app.module.ts file: export function createTranslateLoader(http: HttpClient): TranslateHttpLoader { return new TranslateHttpLoader(http, './ass ...

Enhance the aesthetic appeal of the imported React component with added style

I need assistance with applying different styles to an imported 'notification' component within my header component. The notification component has its own CSS style, but I want to display it in the header component with unique styling. How can I ...

What is the best way to eliminate the # symbol in angular 5 URLs?

Currently, I am working on a project in Angular 5 and I need to remove the hash symbol (#) from my URL. The current URL looks like this: http://localhost:4200/#/product/add. While it works fine after being published on my domain, I encounter a 404 error ...

Why hasn't the variable been defined?

Why am I receiving an error message saying "test is not defined" in this code? Even though I have properly defined the variable in another service file, it seems to be causing issues here. Any insights on what could be going wrong? import { Injectable } f ...

When implementing Angular 6, using a shared module within individual lazy-loaded modules can lead to a malfunctioning app when changes are

Hey there, I've encountered a strange problem that didn't occur when I was using Angular 5. Let me explain the situation: In my App routing module, I have: { path: 'moduleA', pathMatch: 'full', loadChildren: &ap ...

SSL causing Wordpress AJAX call to redirect from HTTPS to HTTP

My AJAX request seems to be encountering a redirection issue to HTTP. Despite trying different solutions like adding a trailing slash and changing the URL to "https" as recommended in similar posts, I am still facing rejection. jQuery.ajax({ url: "https:/ ...

What is the best approach for managing and obtaining accurate JSON responses when working with PHP API and AngularJS 2 services?

Encountering a backend issue with MySQL, wherein one query is producing a specific dataset: {"candidat":[{"ID":1,"nom":"Danny","prenom":"Hariot","parti":"Quamba","departement":"Ukraine","commune":"Chapayeve"},{"ID":2,"nom":"Shari","prenom":"Adamkiewicz"," ...

The error message "window is not defined in Angular Universal" indicates that the window object

While attempting to utilize @nguniversal/express-engine, I encountered an issue in the main.js file after installing and running it. The error message reads: C:\Folder\ssr\dist\ssr\server\main.js:179450 })(window, functio ...

Issue with radio button validation not being triggered upon form submission

I am encountering an issue with validating a radio button in a form. Despite my efforts, I am able to proceed to the next page without selecting a radio button option. However, the validation for the email address field is working correctly. Below is the r ...

Set up a personalized React component library with Material-UI integration by installing it as a private NPM package

I have been attempting to install the "Material-UI" library into my own private component library, which is an NPM package built with TypeScript. I have customized some of the MUI components and imported them into another application from my package. Howe ...

Issue "Value of type '{}' cannot be assigned to parameter of type 'T | (() => T)'" encountered within a React component containing a type parameter

Currently, I am attempting to achieve the following: function SomeComponent<T>({ children }: PropsType) { const [configuration, setConfiguration] = useState<T>({}) } However, I am encountering this issue: The argument of type '{}&apos ...

The Angular material datepicker fails to organize items in a horizontal row

My web application features an Angular Material datepicker, however, I am facing an issue where not all elements are showing up in a row. The view is as follows: Datepicker To prevent any custom CSS from impacting the view, I have removed all customized ...

Is it feasible to utilize GraphQL subscriptions with Azure Functions?

Exploring the potential of implementing GraphQL subscriptions on Azure Functions. Unfortunately, it seems that apollo-server-azure-functions may not be compatible. Are there any other options or strategies to successfully enable this functionality? ...

Utilizing React Higher Order Components with TypeScript: can be initialized with a varied subtype of restriction

I am currently working on creating a Higher Order Component (HOC) that wraps a component with a required property called value, while excluding its own property called name. import React, { ComponentType } from 'react'; interface IPassThro ...

The table is failing to display the values contained within the array

My users list is successfully retrieved from the API and I can see the data in my console. However, when I attempt to map it and display it as a table, it doesn't seem to work as expected. This is the component I'm working with: interface IUser { ...

When running the test, a "is not defined" ReferenceError occurs in the declared namespace (.d.ts) in ts-jest

When running typescript with ts-jest, the application functions properly in the browser but encounters a ReferenceError: R is not defined error during testing. The directory structure: |--app | |--job.ts |--api | |--R.d.ts |--tests | |--job.test.ts ...

Transform a specialized function into a generic function with static typing

First off, I have a network of routes structured like this: interface RouteObject { id: string; path: string; children?: RouteObject[]; } const routeObjects: RouteObject[] = [ { id: 'root', path: '/', children: [ ...

Reset Angular Material autocomplete upon selection

The issue I'm encountering is as follows: when an option is chosen from the autocomplete input, it should not only add a chip to the Angular Material Chips component (which it currently does), but also clear the autocomplete input so that another opti ...

Error arises when attempting to pass interface props to a component in a React Typescript application

I am currently delving into the world of React js and typescript. As part of my learning process, I have created a demo application that allows users to input their name and age. The app features an ErrorModal that should pop up on the screen whenever inco ...

Convert the Angular PrimeNG class into a TreeNode object to avoid the error of trying to access the map property of an

Currently, I am working on a project that was created with JHipster and utilizes Angular 4.3. I want to incorporate the tree component from PrimeNG into this application. My aim is to transform an array of objects into an array of TreeNodes so that it can ...