Angular error code TS2322: Type 'Promise<Dish[]>' is causing issues

I am currently learning Angular 5 on Coursera and facing an issue with the Promise concept. I followed the code from my instructor but encountered an error TS2322 while working on my service file.

import { Injectable } from '@angular/core';
import { Dish } from '../shared/dish'; //this is a class
import { DISHES } from '../shared/dishes'; //these are constants

@Injectable()
export class DishService {

  getDishes(): Promise<Dish[]> {
    return Promise.resolve(DISHES);
  }

  getDish(id: number): Promise<Dish> {
    return Promise.resolve(DISHES.filter((dish) => (dish.id === id))[0]);
  }

  getFeaturedDish(): Promise<Dish> {
    return Promise.resolve(DISHES.filter((dish) => dish.featured)[0]);
  }

Here is how the component utilizes the service:

import { Component, OnInit } from '@angular/core';
import { Dish } from '../shared/dish';
import { DishService } from '../services/dish.service';

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.scss']
})
export class MenuComponent implements OnInit {

  dishes: Dish[];

  selectedDish: Dish;

  onSelect(dish: Dish) {
    this.selectedDish = dish;
  }

  constructor(private dishService: DishService) { }

  ngOnInit() {
      this.dishes =  this.dishService.getDishes()
      .then(dishes => this.dishes = dishes);
  }

}

However, I am encountering the following errors:

ERROR in src/app/dishdetail/dishdetail.component.ts(26,4): error TS2322: Type 'Promise' is not assignable to type 'Dish'. Property 'id' is missing in type 'Promise'. src/app/home/home.component.ts(28,5): error TS2322: Type 'Promise' is not assignable to type 'Dish'. src/app/menu/menu.component.ts(23,4): error TS2322: Type 'Promise' is not assignable to type 'Dish[]'. Property 'includes' is missing in type 'Promise'.

I suspect there might be an issue with my service implementation, but I'm unable to find relevant resources to guide me. Could someone please explain what could be going wrong?

Answer №1

Attempting to assign a promise to this.dishes when it should be a Dish object is causing issues. Make sure to remove the assignment from your code and only set this.dishes after successfully receiving the data:

this.dishService.getDishes()
      .then(dishes => this.dishes = dishes);

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

Should UI conditional changes always be placed directly within the class?

Currently, the class is undergoing changes in color schemes. When the value is set to active, it displays colored text and background accordingly. The same logic applies to other values like rejected, cancelled, expired, and pending. Is this the most eff ...

Setting up WebPack for TypeScript with import functionality

A tutorial on webpack configuration for typescript typically demonstrates the following: const path = require('path'); module.exports = { ... } Is it more advantageous to utilize ES modules and configure it with import statements instead? Or is ...

Detecting hidden child divs due to overflow: hidden in Angular6

Below is the particular issue I am aiming to address. <div class="row" style="overflow:hidden;"> <app-car *ngFor="let car of cars; trackBy: trackByFunction" [car]="car" > </app-car> </div> <button> ...

Guide on invoking an HTML event method from a parent component to a child component

I have the following parent component: JS import { Component, OnInit } from '@angular/core'; import { TaskService } from '../task.service'; import { ViewChild } from '@angular/core/src/metadata/di'; import { CreateNewTaskCom ...

Issue with Angular: Checkboxes resetting to all checked state post form submission

My food item entry form is divided into two tabs. Each tab has a separate form created using JSON configurations, which are then combined together. The issue arises after clicking the save button and the backend validations are triggered. If there are an ...

Stop unwanted clicking on inactive buttons in Angular

I want to make sure that disabled buttons cannot be clicked by users who might try to remove the disabled attribute and trigger an action. Currently, I have this code to handle the situation: <button [disabled]="someCondition" (click)="executeAction()" ...

Measuring the frequency of API calls through HttptestController

I need to track the number of times an API is being called, and I am using HttpTestingController to achieve this. When const req = httpMock.expectOne('/api/getrecords'); fails it('should return one object', () => { var dummyO ...

Best Approach for Executing a Scheduled Task in Angular-Meteor

Currently in the process of developing an appointment scheduling application using angular-meteor. One of the crucial features that needs to be incorporated is the ability to send a text notification to customers who have scheduled appointments. Customer ...

ngx-scroll-event activated, yet remains elusive

After updating my project from Angular 7 to 8 smoothly, I proceeded with the update to Angular 9. Suddenly, the project was unable to find the required [email protected] package, resulting in a "module not found" error: Cannot find module 'ngx-sc ...

Issue with updating state in child component preventing addition to state

Recently, I made the switch to TypeScript in my NextJS project using Create T3 App. One of the components in my app involves updating the state after a Prisma mutation is performed. I attempted to pass the setItems (which was initialized with useState) to ...

SQL Exception: The value for the first parameter is not defined

I'm encountering an issue with a SqlError while trying to retrieve data from my database. It seems like the problem is within my fetchData function where I might not be passing the two parameters (startDate and endDate) correctly. The specific SqlErr ...

Encountering a runtime issue when implementing Ng2-charts within an Angular/Node.js project

I encountered an error while running my Angular4 - Node.js application. The error message states: Can't bind to 'data' since it isn't a known property of 'canvas'. ("iv> ][data]="doughnutChartData" [labels]="doughnutChart ...

Issue with spyOn function being called in Jasmine test for Angular 2

Within the initialization of my Angular component, there is a function: populateForm(id:String, index:number){ let blogs = this.blogsService.returnBlogs() blogs.map((blog:Blog)=>{ blog._id === id ? this.blogsService.populateForm.next({blog: ...

Issue with hardhat failing to detect balance transfer from smart contract

I am currently in the process of creating tests for a smart contract that I have developed. Below is a simplified version of the smart contract: Please Note: I have hard-coded the value to ensure accuracy regarding the amount leaving the contract. functio ...

Ways to transform an ISO string formatted date time into the following hour

I have a function that converts my date to RFC3339 format, but I want it to be converted to the upper time limit. Could someone please help me figure out how to convert it to the upper limit? const date = new Date(); // converting to RFC 3339 format ...

Resolving conflicts between TypeGraphQL and Prisma 2 types

Currently, my development stack consists of TypeGraphql, Prisma 2, an Apollo Express server, and a PostgreSQL database. To facilitate the generation of TypeScript types, I utilized Prisma to introspect my database and generate types from the schema.prisma ...

Issue with Ionic Map and location services

After extensively searching for solutions to my current error, I have found that all existing solutions are outdated and do not work for me. The issue began when I tried to incorporate the user's current location into my app, which utilizes Google Map ...

The values of object keys are printed in a random order

Hey everyone, I have an object that looks like this var dates = { '2021-09-15': 11, '2021-09-16': 22, '2021-09-17': 38, '2021-09-18': 50, '2021-09-19': 65 }; I am trying to display the valu ...

Remove the icon that indicates severity in PrimeNG

Is there a way to eliminate the X icon from the page? <p-message severity="error" text="*" *ngIf="!form.controls['name'].valid "> </p-message> ...

Iterate through values in a Typescript loop

Incorporating nextjs, React, and Typescript into my project. I am aiming to extract values from an array of objects. Here is a snippet of my data in data.json: [ { "id": "value", “name”: “value”, “type”: “value” } ...