Angular2教程:服务

时间:2017-05-27 11:54:56

标签: angular angular-cli angular-promise

我正在关注Angular.io网站上的教程“Angular Tour of Heroes”。 我使用Angular CLI设置项目(请参阅本文末尾的环境版本)。

我被困在point 5 (services): 使用教程提供的相同文件,我在'hero.service.ts'的第9行中收到以下错误:

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[]'.

这是服务的代码(文件'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);
  }
}

这是组件(app.component.ts)的片段,它在服务承诺解决时起作用:

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

我刚刚在教程中看到了this other post about a similar error,但错误描述了有关属性“长度”而不是“然后”的投诉:

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

正如我所说,我被困在这里,我不知道我的环境是否与错误有关。我正在使用Ubuntu 14.04(带有crouton Chroot的ARM Chromebook),node v7.10.0npm 4.6.1angular 4.1.3angular-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

0 个答案:

没有答案