Yuriy Lukinskikh
Yuriy Lukinskikh

Reputation: 65

Angular error TS2322: Type 'Promise<Dish[]>

I learn Angular 5 at Coursera and have problem with Promise theme. I just repeat a code of lector and have an error TS2322. Here is my service file.

import { Injectable } from '@angular/core';
import { Dish } from '../shared/dish'; //it's a class
import { DISHES } from '../shared/dishes'; //it's const

@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]);
  }

And component which use 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);
  }

}

And I get 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 think something wrong with my service, but I can't find the topics which help me. Please, explain me what's wrong.

Upvotes: 2

Views: 973

Answers (1)

TheUnreal
TheUnreal

Reputation: 24472

You are trying to set this.dishes to a promise while it's a Dish. Remove the assignment in your code and set this.dishes only after you receive the data:

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

Upvotes: 4

Related Questions