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

Determine the route parameter name based on the path string, for example, '/posts/:id'

My Route interface has a params object, and I'm looking to ensure type safety on that params object. For example: If we have a route config like this: { post: { path: 'posts/:id', } } navigate({ name: 'post', params: { wr ...

When an import is included, a Typescript self-executing function will fail to run

Looking at this Typescript code: (()=> { console.log('called boot'); // 'called boot' })(); The resulting JavaScript is: (function () { console.log('called boot'); })(); define("StockMarketService", ["require", "exp ...

Unable to access default root folder after renaming wwwroot in Web API .NET Core

I have made some changes to my .net core web api application. I decided to rename the wwwroot folder to "clientapp" and use that folder as the output destination for an angular application build. Whenever I run the command: ng build it now compiles the f ...

Reacting like sticky bottoms and tops

I'm working on a react/tailwind project that involves a component I want to be fixed at both the top and bottom of the screen. In simpler terms, there's an element that I need to always stay visible even when the user scrolls up or down the page ...

The error message "Uncaught ReferenceError: exports is not defined and require" indicates that

I am currently developing an app using angularjs and typescript, but I've encountered a persistent error that has me stumped. Below is the snippet of my code: export var NgApp = new application.Startup(); ///<reference path="../../../../../typin ...

Tips for properly defining path names in loadChildren for lazy loading in Angular 2 NgModules

When setting correct path names for loadChildren in the app-routing.module file within an Angular 2 NgModule, I encountered some issues. Despite following the NgModule concept outlined on the Angular main website, I still couldn't find clear informati ...

What is the best way to add a hyperlink to a cell in an Angular Grid column

I need help creating a link for a column cell in my angular grid with a dynamic job id, like /jobs/3/job-maintenance/general. In this case, 3 is the job id. I have element.jobId available. How can I achieve this? Here is the code for the existing column: ...

What could be causing the global npm package to not be utilized for module dependencies?

My typescript and ts-node are already installed globally. In my package.json file, I have the necessary configurations to run tests with npm test. Everything works fine since ts-node and typescript are installed as local modules. { "name": "two_sum", ...

Refresh PrimeNG dataTable without reloading the table

Currently, I am implementing the functionality of adding new rows to a dataTable in my template. Here is the code snippet from the component: rows: any = {} newrow: any = {} addNewRow(key: string) { let rows = {...this.rows} let newrow = {_key: Math ...

VS Code couldn't locate a definition for the function 'myMethod'

For some reason, I am unable to find a definition for 'myMethod' in VS Code. In my angular projects, after importing one project into VS Code, I can easily navigate to definitions using the 'F12' key. However, when I import another pro ...

The parameter label is being detected as having an any type, as specified in the Binding element 'label'

Currently, I am referencing an example code snippet from react-hook-form. However, upon implementation, I encounter the following error: (parameter) label: any Binding element 'label' implicitly has an 'any' type.ts(7031) The example c ...

The Angular router-outlet is refusing to display any content

I am new to Angular and currently learning through a lecture with hands-on practice. I have written the code below as instructed by my teacher, but it's not displaying anything on the screen. Can someone please assist me? app.module.ts : @NgModule({ ...

What is the best way to inform TypeScript when my Type has been altered or narrowed down?

In my application, I have a class that contains the API code: export class Api { ... static requestData = async ( abortController: React.MutableRefObject<AbortController | null> ) => { // If previous request exists, cancel it if ...

Steps to retrieve the value stored in a variable within an Angular service from a separate component

How can I effectively share question details and an array of options from one component to another using services? What is the recommended method for storing and retrieving these values from the service? In my question-service class: private static ques ...

Data binding in Angular 2: Connecting components

Is it possible to establish a connection between two components that are working with related objects? One of the components is dedicated to filtering, while the other displays the data results. By applying filters such as checkboxes, the displayed data ...

The function userRole consistently returns "user" regardless of the role being admin

I am facing an issue with the getTeamMembers() method while trying to identify which members are admins in a private team. Even though I am logged in as an admin, the userRole value always shows as "user". Can anyone assist me with this problem? import { ...

Capturing user audio on the client side with Angular

Is there a built-in feature in Angular to record client-side audio input? I have attempted using the p5 library, but it is encountering integration problems. ...

Changing the mouse cursor dynamically with Angular programming

What is the recommended approach for changing the mouse cursor programmatically in Angular? For instance: HTML: <div [style.cursor]="cursorStyle">Content goes here</div> or <div [ngStyle]="{ 'cursor': cursorStyle ...

How to update an Angular 2 component using a shared service

My question is regarding updating components in Angular 4. The layout of my page is as follows: Product Component Product Filter Component Product List Component I am looking to link the Product Filter and Product List components so that when a user c ...

Typescript error message TS2314: One type argument is required for the generic type 'Array<T>'

I recently started my journey in learning typescript and have written some basic code. class Learning { subjects: Array[string]; hoursPerDay: number; constructor(subj: Array[string], hrs: number) { this.subjects = subj; thi ...