Angular2 Tutorial: Promise error (type not assignable) in Service
Asked Answered
L

0

6

I'm following the tutorial "Angular Tour of Heroes" at the Angular.io site. I've setup the project with Angular CLI (see environment versions at the end of this post).

I'm stuck at point 5 (services) : using the same files provided by the tutorial, I get the following error in line 9 of 'hero.service.ts':

Failed to compile.

/home/myuser/angular-tour-of-heroes/src/app/hero.service.ts (9,4): Type 'Hero[]' is not assignable to type 'Promise<Hero[]>'.
  Property 'then' is missing in type 'Hero[]'.

This is the code of the service (file 'hero.service.ts'):

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

And this is a snippet of the component (app.component.ts) that acts when the service promise resolves:

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;
  }
}

I just saw this other post about a similar error in the tutorial, but the error depicted there complaints about property 'length' instead of 'then':

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

As I said, I'm stuck here, I don't know if my environment could have something to do with the error. I'm using Ubuntu 14.04 (ARM Chromebook with crouton Chroot), node v7.10.0, npm 4.6.1, angular 4.1.3, angular-cli 1.0.6 :

$ ng --version
    _                      _                 ____ _     ___
   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
               |___/
@angular/cli: 1.0.6
node: 7.10.0
os: linux arm
@angular/common: 4.1.3
@angular/compiler: 4.1.3
@angular/core: 4.1.3
@angular/forms: 4.1.3
@angular/http: 4.1.3
@angular/platform-browser: 4.1.3
@angular/platform-browser-dynamic: 4.1.3
@angular/router: 4.1.3
@angular/cli: 1.0.6
@angular/compiler-cli: 4.1.3
Landmass answered 27/5, 2017 at 11:54 Comment(2)
Try to restart ng serve. I have had similar issues, which then were gone.Mattson
webpack: Compiled successfully after restart. Thanks!Landmass

© 2022 - 2024 — McMap. All rights reserved.