ERROR: The 'then' property is not found in the 'Hero[]' type

Code from the app.component.ts file

import { Component, OnInit } from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [HeroService]
})

export class AppComponent 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();
  };
    onSelect(hero: Hero): void{
    this.selectedHero = hero;
  };
}

Code snippet from the hero.service.ts file

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

@Injectable() 
export class HeroService { 

    getHeroes(): Promise<Hero[]> { 
        return Promise.resolve(HEROES); 
    } 
}

What is the solution to fix this issue?

Answer №1

Upon encountering the same issue, I conducted a search for solutions and discovered that your code mirrors mine with no errors present. A simple restart of ng serve resolved the compilation successfully. source: Angular2 Tutorial: Promise error (type not assignable) in Service

Answer №2

The promise returned by this.heroService.getHeroes() method has been successfully resolved.

Consider refactoring it to:

this.heroes = this.heroService.getHeroes();

Answer №3

Rather than:

fetchCharacters(): Promise<Character[]> { 
  return Promise.resolve(CHARACTERS); 
} 

Give this a shot:

fetchCharacters(): Promise<Character[]> {
  return new Promise(resolve => {
    resolve(CHARACTERS);
 });
}

This method is effective

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

Implementing a builder pattern with @Ngrx/Store

Feeling a bit uncertain... I'm wondering if it's suitable, awesome or not advisable to employ a builder pattern to retrieve API response and then apply the builder pattern on that response before storing it in @ngrx/store? And later on when acces ...

Error: NgbAlert from ng-bootstrap cannot resolve all parameters when used with angular2-meteor

I am currently working on a meteor project that utilizes Angular as its front end. I am facing some challenges in importing @ng-bootstrap/ng-bootstrap into my project correctly. Here are the details of my setup... Meteor Version: 1.6, Angular Version: 5.1 ...

"Enhance performance in React by optimizing the re-render of nested functional list components

Is it expected for the custom component CheckboxLabels to not retrieve a different checked prop after each invocation of the handleCheckboxChange function? Currently, I am unable to update the state of the clicked checkbox to be "checked" before closing ...

When the fullscreen modal is opened, the initial image displayed is not the same as the one that was clicked on

Seeking assistance: I've been struggling with a problem for quite some time now and could really use some help from you guys. My issue involves an 'AngularJS' webapp that retrieves posts from an 'FB page' via 'OpenGraph' ...

Getting pdfMake to function seamlessly with Angular 4 and webpack

I encountered an issue while trying to integrate pdfMake into my Angular 4 application. Despite following a guide on Stack Overflow, I faced an error due to the use of webpack. Could not find a declaration file for module 'pdfmake/build/pdfmake' ...

Sending data from Spark to my Angular8 projectLearn how to seamlessly transfer data from your

I am utilizing Spark 2.4.4 and Scala to retrieve data from my MySQL database, and now I am looking to showcase this data in my Angular8 project. Can anyone provide guidance on the process? I have been unable to locate any relevant documentation so far. ...

Exclusive Vue3 Props that cannot be used together

How can a component be created that accepts either json with jsonParserRules or jsonUrl with jsonParserRulesUrl, but not both? It would be ideal if the IDE could provide a warning when both props are specified. Example of an Attempt that does not Work < ...

Neither the child nor the parent are showing the ng-content

I'm working on a project with a child-parent structure and I have the following components: <app-parent> parent component <ng-content select=["parent"]></ng-content> <app-child></app-child> </app-par ...

Create duplicates of both the array and its individual elements by value

I'm having trouble figuring out how to properly copy an array along with all its elements. In my model, I have a name and options, both of which are strings. This is what I currently have: const myArrayToDuplicate = [myModel, myModel, myModel] My ...

Optimizing performance in React: A guide to utilizing the Context and useCallback API in child

Utilizing the Context API, I am fetching categories from an API to be used across multiple components. Given this requirement, it makes sense to leverage context for managing this data. In one of the child components, the categories can be expanded using ...

NestJS Bull queues - Failing to secure job completion with a lock

I am currently utilizing Bull in combination with NestJS to manage a jobs queue. Within the process handler, I aim to designate a job as failed instead of completed. However, it appears - after carefully reviewing the documentation as well - that the Job#m ...

How can I effectively implement a withAuth higher order component (HOC) in TypeScript within Next.js?

Currently, I am working on a Next.js application and implementing the next-auth package. My goal is to develop a Higher Order Component (HOC) that can determine if the component has an active session or not. Along with this, I am utilizing eslint for code ...

Error in Angular 7: ActivatedRoute paramId returns null value

On page load, I am trying to subscribe to my paramsID, but when I use console.log(), it returns null. I am currently working with Angular 7. Here is my TypeScript code: import { Component, OnInit } from '@angular/core'; import { Activat ...

Error: The variable "dispatcher.useMemo" is not recognized as an object

I encountered an issue while trying to incorporate InversifyJS with MobX in my React Native project. The error message I received was: ERROR TypeError: null is not an object (evaluating 'dispatcher.useMemo') Surprisingly, I have not utilized ...

Is there a way to retrieve the zoom level in Highmaps and are there any events related to zooming in Highmaps

Is there a way to trigger a zoom event in Highmaps? Furthermore, how can the current zoom level of the map be retrieved? Adjusting the zoom level is straightforward, but extracting it proves to be more challenging. After exploring the API documentation, ...

Searching within an Angular component's DOM using JQuery is restricted

Want to incorporate JQuery for DOM manipulation within Angular components, but only want it to target the specific markup within each component. Trying to implement Shadow DOM with this component: import { Component, OnInit, ViewEncapsulation } from &apo ...

Angular File Sorting Error in Gulp detected

After including .pipe(angularFilesort()) in my gulp script, the task runs wiredep but never proceeds to the default task. It just stops after executing wiredep. However, if I remove .pipe(angularFilesort()), the script works perfectly fine. Can someone h ...

How to trigger the external opening of a md-select in Angular 2

Is there a way to trigger the opening of an md-select menu from a button using code similar to this? <md-select placeholder="Cuestionario" (ngModelChange)="set_survey($event)"> <option [ngValue]='undefined' disabled selected>Selec ...

Issues with the persistence of ManyToOne relationships in Spring MVC and Angular AngularJS dropdown lists

Issue: Currently, I am facing an issue with the persistence of data in my Purchase Order system. The problem arises when I submit a form for creating a new PO using AngularJS. The form contains multiple fields and drop-down lists, with one example being th ...

Guide to iterating through an Observable<Object[]> to generate an array of objects

Google Firestore collection named users is structured as follows : { "contactNumber":"0123456789", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88e2e7e0e6ece7edc8efe5e9e1e4a6ebe ...