Assignment of type 'Object' is incompatible with type in new HttpClient / HttpGetModule implementation within Angular

After following the angular tutorial, I decided to test out the new httpClient.Get method. However, it seems that no matter what, it always returns results of type Object.

// HttpClient 
getHeroes2 () {
   this.http.get<Hero[]>(this.heroesUrl) 
     .subscribe((data: Hero[]) => this.takeHeros2(data)); 
}

takeHeros2(heroes: Hero[]) {
  console.log(heroes)
}

Upon inspecting the parameter heroes in the method takeHeros2(), I found that it is of type Object[] instead of Hero[]. The result of heroes in debugger can be seen here.

This issue is puzzling to me and I am struggling to understand why it is happening.

Answer №1

When you use <Hero[]>, you're basically informing the compiler:

Hey, when I call this method, it will give me an array containing objects. And these objects will follow the same structure as the Hero class

The essence here is 'objects with the same structure'. This means that they will remain as generic objects. If you want your objects to be specifically of type Hero, you can do the following:

getHeroes2() {
   this.http.get<Hero[]>(this.heroesUrl) 
     .map(hero => Object.assign(new Hero(), hero))
     .subscribe((data: Hero[]) => this.takeHeros2(data)); 
}

This utilizes the map operator from rxjs, which creates a new Hero object for each object in the result array and returns it

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

After subscribing, creating the form results in receiving an error message that says "formgroup instance expected."

I am currently working on a project using Angular 6 to create a web page that includes a form with a dropdown menu for selecting projects. The dropdown menu is populated by data fetched from a REST API call. Surprisingly, everything works perfectly when I ...

Transferring functionality from a child component to a parent component

I have a Base Component called ListComponent and a ParentComponent named Businesses2ListComponent. The concept is to have multiple types of Lists with tables that all stem from the ListComponent. This requires passing the correct service accordingly. In t ...

Is it possible to locate a Typescript class only when there are no references to its properties?

Currently, I am utilizing TypeScript 2.0 within VSCode and although the highlighted errors are being confirmed by the TypeScript compiler, they all point to a module that I am importing: import * as els from 'elasticsearch'; The module elastics ...

Why does Typeorm consistently encounter insertion failures when attempting to insert into two tables, and why does Math.random() continuously return the same number?

Here is the code snippet I am working with: import { getRepository } from "typeorm"; import { NextFunction, Request, Response } from "express"; import { Users } from "../entity/Users"; import { Verify } from "../entity/Ve ...

Exploring the distinction between "() => void" and "() => {}" in programming

Exploring TS types, I defined the following: type type1 = () => {} type type2 = () => void Then, I created variables using these types: const customType1: type1 = () => { } const customType2: type2 = () => { } The issue surfaced as "Type ...

Encountering an issue while attempting to input a URL into the Iframe Src in Angular 2

When I click to dynamically add a URL into an iframe src, I encounter the following error message: Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'SafeValue%20must%20use%20%5Bproperty%5D' To ensure the safety of the ...

Encountering difficulties during the installation of Angular 6.0.8

We encountered an error during the Angular installation process which resulted in Angular not being installed correctly. D:\software\node-v8.11.2-win-x64>npm install -g @angular/cli D:\software\node-v8.11.2-win-x64\ng -> ...

When working with TypeScript for initial data, you have the choice between using interface types or class types. Which approach is the

When working with initial data in TypeScript, you have the option to use either an interface type or a class type. Which approach is preferable? export interface Item{ text: string, value: number } itemModel: ItemComboBox = { value:'valu ...

Issue encountered when attempting to develop a countdown timer using Typescript

I am currently working on a countdown timer using Typescript that includes setting an alarm. I have managed to receive input from the time attribute, converted it using .getTime(), subtracted the current .getTime(), and displayed the result in the consol ...

Exploring the concept of ngForm and ngModel within template-driven forms in Angular

Hello, I have recently delved into the world of angular and ionic development. I've learned that interpolation and property binding are used to pass data from the class to the template. Interpolation is limited to strings, whereas property binding su ...

Best practices for handling HTTP requests in Angular 5

I'm currently developing multiple applications using Angular 5. My aim is to adhere to all the dos and don'ts of Angular. However, I'm facing some confusion regarding a few things. 1) What is the difference between this... this._http.g ...

Should I use Object.assign or define class properties?

Currently in the process of developing an angular application that interacts with the twitch API. The API returns data in various formats, some of which I need to parse and save into specific classes. My main concern is understanding the potential drawbac ...

Does Vue.js have its own version of Angular's named templates feature?

Check out this snippet of Angular code: <ng-container *ngIf="someCondition; else spinner"> Show Data </ng-container> <ng-template #spinner> Show Spinner </ng-template> Do you know if there is a similar vue.js equ ...

React is unable to identify the property that was passed to a styled-component in Material UI

Custom Styled Component Using Material-UI: import { Typography } from '@material-ui/core'; const CustomText = styled(Typography)<TextProps>` margin-bottom: 10px; color: ${({ textColor }) => textColor ?? textColor}; font-size: ${( ...

Exploring Date Comparison in Angular 2

I'm currently exploring the most effective way to compare dates in Angular 2 using TypeScript 1.8.7. Consider the following: startDate: Date; endDate: Date; if(this.startDate.getTime() === this.endDate.getTime()){ //perform tasks here } else { ...

Issue with mapping HttpClient subscribe method in Angular 5

Retrieve some data from an API and store it in a JSON array: [{"id":19,"date":{"date":"2017-09-10 10:58:40.000000","timezone_type":3,"timezone":"Europe/Paris"},"user":{"nom":"castro","prenom":"diana","mail":"<a href="/cdn-cgi/l/email-protection" class= ...

The Karma testing feature in Angular Quickstart encounters issues right from the start

When attempting to run karma tests after a clean install of the official Angular quickstart on Windows 10, I encountered an issue. Following a series of four commands, here is what happened: C:\projects\temp>git clone https://github.com/angul ...

Switching Angular repository to download node_modules dependencies from internal company source: A step-by-step guide

Within my company, we have an internal artifactory where all the dependency libraries must be sourced from. It is not possible for me to download them from the internet using 'npm install'. Upon examining the package-lock.json file, I noticed th ...

Angular 6 is throwing an error stating that the 'publish' property is not found on the type Observable<string>

Currently, I am working on my initial Angular project using Angular 6. To streamline the process of handling errors in one central location, I have decided to incorporate Error Handling by referencing this insightful article on Medium From the code snipp ...

Can you explain the distinction between App: React.FunctionComponent and App = (): React.FunctionComponent()?

Currently exploring the depths of typescript. Can someone clarify the distinction between these two code snippets: const App: React.FunctionComponent<CustomProps> = (props: CustomProps) => { return <div>Hello World!</div>; }; and: ...