TS2339: The 'map' property is not available on the 'Object' type

I'm currently working with the following code snippet:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import { map } from 'rxjs/operators';

interface SingleParamConstructor<T> {
  new (response: any): T;
  id: T;
}

@Injectable()
export class RestProvider<T> {
  baseUrl:string = "http://localhost:3000";

  constructor(private ctor: SingleParamConstructor<T>, private httpClient : HttpClient) { }

  public getEntities<T>(): Observable<T[]> {
    return this.httpClient
      .get(this.baseUrl + '/products')
      .pipe(map(entities => {
        return entities.map((entity) => new this.ctor(entity));
      }))
      .catch((err) => Observable.throw(err));

  }
}

Upon testing the code, I encounter the error

TS2339: Property 'map' does not exist on type 'Object'
.

The line causing the issue is:

return entities.map((entity) => new this.ctor(entity));

I am looking for help in understanding where I went wrong and how to successfully utilize the map function on entities.

Answer №1

When using Angular's get method, it's important to specify the type of data being received to avoid any confusion. If not specified, Angular will assume it is an anonymous object, as outlined in the Angular documentation on httpclient parsing. Additionally, when upgrading to rxjs 6, make sure to use catchError instead of .catch:

import { catchError, map } from 'rxjs/operators';
import { of } from 'rxjs';

// ...

public getEntities<T>(): Observable<T[]> {
  return this.httpClient
    // specifying that it's an array
    .get<T[]>(this.baseUrl + '/products')
    .pipe(
       map(entities => {
        return entities.map((entity) => new this.ctor(entity));
       }),
       catchError((err) => of(err))
    )
}

Answer №2

I believe that the result you are receiving (entities) is of type object, which means it cannot be iterated over.

To troubleshoot this issue, try replacing pipe(map with pipe(tap and use console.log to inspect the data coming from the server,

.pipe(tap(entities => console.log(entities));

If you need to loop through the properties of an Object, you can use Object.keys(myObj) which will return an array for iteration.

I hope this explanation clarifies things for you.

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

Leverage the power of Typescript to flatten a JSON model with the help of Class

Currently, I'm exploring how to utilize the class transformer in TypeScript within a Node.js environment. You can find more information about it here: https://github.com/typestack/class-transformer My goal is to flatten a JSON structure using just on ...

Karma and Jasmine are not recognizing the 'md-icon' element in Angular2 material

I am currently developing an Angular2 application using the following versions: @angular/material 2.0.0-alpha.11-3 angular-cli 1.0.0-beta.19-3 karma 1.2.0 karma-jasmine 1.0.2 While running the application, everything works fine except for some specific te ...

React-pdf has encountered a situation where more hooks were rendered compared to the last render cycle

I am currently integrating react-pdf to display a PDF document in a web view. The React application is built with TypeScript and Next.js. This is the code I have written so far: const MyPage: NextPage = () => { // some code here const [numPages, setN ...

"Efficient ways to calculate the total sum of an array of objects based on a specific property

I currently have a straightforward method that calculates the total sum of an object array based on one of the properties. const calculateSum = <T extends object, K extends keyof T>(array: T[], property : K) : number =>{ let total = 0; if ( ...

What is the best way to bring a module into a dialog in Angular (8)?

I've developed a reusable dialog component for my Angular project, but I'm facing an issue when trying to import modules inside the dialog. Strangely, the page stops functioning properly. Here's the hierarchy of my project: https://i.sstat ...

Retrieve validators and values from an Angular FormControl

Would you happen to know how to determine if an Angular FormControl contains a particular validator and access its value? For example, suppose I have a form control set up like this: testControl: new FormControl(null, [Validators.required, Validators.minL ...

Issue: UNSUPPORTED: The keyword "id" is not supported, please use "$id" for the schema ID after upgrading to Angular13

After upgrading from Angular 12 to Angular 13, I encountered an error while running my e2e tests. How can I go about identifying the root cause of this issue? I am able to compile with 'ng build'. /opt/wdio/node_modules/@angular-devkit/core/nod ...

Changing environment.ts with custom schematics in angular-cli

Currently, I am working on creating customized schematics for our Angular Cli project. One of the tasks involves adding properties/variables to both the environment.prod.ts and environment.dev.ts files. I am curious if anyone has experience with this and h ...

Ways to incorporate style links in Angular v2 components?

Currently, I am working through the Angular tutorial available on their website. In my quest to create various components, templates, and styles, I have hit a roadblock. The issue lies in incorporating my styles into the components using the 'styleUR ...

Using FormArray in Angular 2 with ControlValueAccessor

My child component manages an array of input controls and I would like to implement a form control over this child component. I am passing an array of JSON objects and I am wondering what is the correct way to bind the parent form to the child component&a ...

Can a React function component be typed with TypeScript without the need for arrow functions?

Here is my current React component typed in a specific way: import React, { FunctionComponent } from "react"; const HelloWorld : FunctionComponent = () => { return ( <div> Hello </div> ); } export default HelloWorld; I ...

Transfer an object to $state.go

I'm having trouble solving this issue. Here's the state I am working with: var myState:ng.ui.IState = <ng.ui.IState> { url: '/new/{order.orderNumber}', controller: 'OrderController', controll ...

How can I configure React Router V6 to include multiple :id parameters in a Route path, with some being optional?

Currently, I am utilizing react-router@6 and have a Route that was previously used in V5. The route is for vehicles and always requires one parameter (:id = vehicle id), but it also has an optional second parameter (:date = string in DD-MM-YYYY format): &l ...

Troubleshooting issues with setting errors on a FormGroup instance in Angular Reactive Forms are proving to be more challenging

Currently I am working with Angular 4.4.3 reactive forms to create custom validation for a group of controls within a form. As per the documentation on AbstractControl.setErrors, this method updates the errors property of the AbstractControl that it's ...

Experiencing the error "f.ngOnChanges is not a function in target es5" while using Angular4

Encountering an issue f.ngOnChanges is throwing an error The problem arises when my tsconfig.json file is configured to target es5. However, everything works fine if I set the target to es6. Is there a way to make ngOnChange function properly with es ...

Expanding User Type to Include Extra User Data Using NextAuth.js

I encountered a dilemma where I needed to include the "profile" property in my section object to cater to different user personas in my application. However, despite retrieving the logged-in user's data from the backend and storing it in the NextAuth. ...

Centering on request, Google Maps adjusts its view to focus on

When I select a row, I want to set the map center to the provided coordinates in Primeng. The issue is that while this.options works fine in ngOnInit, it doesn't work when called in the showCords() function. Below is my code: gmap.component.ts im ...

The pipe operator in RxJS is never executed in the Observable fork

I am attempting to execute and retrieve values from an array of observables (each obtained from literalsService) using a pipe. Below is the code snippet: translateLiterals() { const literalsToTranslate: string[] = [ 'certificate_title', ...

What is the best way to selectively pass certain values to the args object?

Is there a way in TypeScript to pass only one argument into args and have other values be default without using "args = {}" or declaring defaults within the function to avoid issues with intellisense? function generateBrickPattern ( wallWidth: number, ...

What is the best way to add items to arrays with matching titles?

I am currently working on a form that allows for the creation of duplicate sections. After submitting the form, it generates one large object. To better organize the data and make it compatible with my API, I am developing a filter function to group the du ...