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

亡梦爱人 提交于 2019-12-01 17:31:16

问题


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

来源:https://stackoverflow.com/questions/44216533/angular2-tutorial-promise-error-type-not-assignable-in-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!