An error occurred in Angular2 when attempting to resolve a Promise: The type 'Promise<Hero[]>' is not compatible with the type 'Hero[]'

Recently updated.

Currently, I am working through an Angular2 tutorial which can be found at this link

Highlighted below is the code snippet for calling the HeroService from heroes.component.ts,

Heroes.component.ts

import { Component , OnInit } from '@angular/core';

import { Hero } from './hero';

import { HeroService } from './hero.service';



@Component({
  selector: 'my-heroes',
  template: `


        <h2>My Heroes</h2>
        <ul class="heroes">
            <li *ngFor="let hero of heroes">
                 <span class="badge">{{hero.id}}</span> {{hero.name}}
            </li>
         </ul> `,

})

export class HeroesComponent implements OnInit {
    title = 'Tour of Heroes';
    heroes: Hero[];
    selectedHero: Hero;

    constructor(private heroService : HeroService ){

    }

    getHeroes(): void{
      this.heroService.getHeroes().then(heroes => this.heroes = heroes);
    }

    ngOnInit(): void{
        this.getHeroes();
    }


}

The following block of code contains the getHeroes() call defined in HeroService

HeroService.ts

import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';

@Injectable()
export class HeroService{
    getHeroes() { 
       return Promise.resolve(HEROES);
     }
}

Upon compilation, I encountered the following error message :

Error TS2322: Type 'Promise' is not assignable to type 'Hero[]'. Property 'length' is missing in type 'Promise'.

Please advise on how to resolve this issue. Thank you.

Answer №1

By modifying heroes: Hero[]; to heroes: any;, the problem is resolved, but an error is displayed in the console as ngFor only supports iterables. In the end, the code compiles successfully and the application runs, although there is a minor issue that I find somewhat bothersome.

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

What causes my slider to speed up with an increase in items and slow down with fewer items in bxslider?

Find more information here jQuery('.homepage_slider').bxSlider( { minSlides: 1, maxSlides: 4, slideWidth: 200, slideMargin: 30, ...

What is the reason behind the majority of marketing tags (like Omniture, XE, etc) being implemented using document.write()?

Could this be a Repeat: Why use document.write? Despite the drawbacks of using document.write(), why do most tracking and marketing tags still utilize it? I have pondered this question extensively, and the only reasonable explanation I can think of i ...

What is the correct way to interpret a JSON file using TypeScript?

Encountering Error Error TS2732: Cannot locate module '../service-account.json'. It is suggested to use the '--resolveJsonModule' flag when importing a module with a '.json' extension. import serviceAccountPlay from '../ ...

Experiment with a map function from RxJS within an HTTP request

Currently, I am in the process of testing an Angular service that includes a private mapper method. Upon review, it appears that this method has not been adequately tested for coverage. My objective is to create a mock for this method within the RxJS map f ...

Utilizing the power of JavaScript to specifically prevent the default behavior within an ASP server control

An ASP.NET server control is used in the code snippet below: <asp:HyperLink Visible='<%# (GetAnswer(Eval("AnsQID"))) != 1 %>' ID="HyperLink1" runat="server" NavigateUrl="#" ToolTip='Like this answer' onclick="javascript:( ...

Getting the autogenerated document ID from Firestore - A Step-by-Step Guide

When creating my document, I rely on the auto-generated ID. However, after setting it, I find that the retrieved ID is different from the one in the Firestore Database. await admin.firestore().collection("mycollection").doc().set(mydata) .then(doc = ...

Add a new element dynamically and update its content on the fly

I am looking to clone certain elements and modify the text inside them using a regex. Here is my progress: (working fiddle - http://jsfiddle.net/8ohzayyt/25/) $(document).ready(function () { var divs = $('div'); var patt = /^\d&bso ...

Utilizing Promises with Multiple .then() in JavaScript

I'm currently in the process of creating an array structure. In this structure, we have different parts and each part contains articles. What I've done is create a promise to gather all the parts using .then(), then I need to iterate through eac ...

Passing Data from Child to Parent Components in ReactJS

I'm new to React and JavaScript, currently working on a website. I've encountered an issue with passing data between components from child to parent. Here's the scenario: In my App.js script, I'm using react-router-dom for routing. I ...

The PUT rest service does not function in AngularJS version 1.0.8

I am facing an issue with my AngularJS application that has a CRUD Rest service. While the Create, Read, and Delete methods are functioning properly, the PUT method is not working. I have searched on Stackoverflow and found similar problems with accepted s ...

Securing API endpoints in a React/Redux application using proxy techniques

Ensuring the security of my react/redux application is a top priority for me. I've noticed that my api url is exposed to the public inside the bundled app.js file, which raises some concerns. After doing some research, I discovered that some developer ...

Conceal the Initial Data Point in a Series on HighCharts

Is there a way to toggle the visibility of specific year columns in a chart using checkboxes? I've tried using the .hide() method but it doesn't seem to work for individual data points within the series. For example, I want to hide the 2018 colum ...

Implement javascript functionality for every hyperlink on a website

Good day! I am curious to know if there is a way to automatically incorporate a JavaScript function to all links or classes on a webpage. Specifically, I am interested in adding the following JavaScript action: "PlayFlashSound();". This would mean that all ...

Reactjs encountered a problem with the click event

I seem to be facing a small issue with my react component code. I can't seem to figure out what's wrong. Here's the component code: import React, { Component, PropTypes } from 'react'; import styles from './Menu.css'; im ...

Transferring data between components: Comparing Passing References and Using Subjects

Question: Is passing variables by reference between Angular components a better option than using BehaviorSubjects? I'm currently developing a diary application in Angular 8 with two components (Navbar and Dashboard) and a service (EntryService). Th ...

What is the best way to retrieve the outcomes of .query within a class?

Currently, I am working on a NodeJS application using coffee script. My objective is to save the results of a sql query executed by a class into a variable that can be returned by that same class. This is what I have so far: class dataBase mySQL = requ ...

Utilize Angular 2 to upload and access files directly on the client side

How can I obtain log file(s) from a user so that I can analyze them? Is there a way to create a drop area where the user can upload a file, and then I can read it using JavaScript? I am currently using Angular2 rc5 and have node.js running on the backend, ...

Combining two JSON datasets using specific fields in Javascript

Two JSON inputs are provided: [ { userId: 32159, userFirstName: "john", userLastName: "doe", plans: [ ] }, { userId: 32157, userFirstName: "dave", userLastName: "mess", plans: [ ] } ] and [ { userId: ...

The disparity between dynamically generated HTML and static HTML is evident

Having trouble understanding why the dynamically generated HTML is different from the static HTML. Even though the output looks the same in the developer tools. I'm looking for a way to make the static HTML appear like the dynamically added HTML, wit ...

Is there a way to connect to a function that has been sent to a child component through a prop in order to invoke it within a function in the child component?

I'm currently facing an issue with accessing the function stored in the closeModal prop that is passed to the child component QRScan. Any advice on how to properly bind and call this function would be greatly appreciated. I attempted to use this.prop ...