'Observable <hero []>'不能分配给'Hero []'

时间:2018-05-07 13:34:57

标签: angular rxjs observable

我正在关注Angular的Tour of Heroes Tutorial,现在我正在尝试将observable集成到我的项目中。将我的hero.service.ts文件更改为此后

import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { Observable } from 'rxjs/Rx';
import { of } from 'rxjs/observable/of';

@Injectable()
export class HeroService {

  constructor() { }

  getHeroes(): Observable<Hero[]> {
    return of(HEROES);
  }
}

我没有收到以下错误

  

src / app / heroes / heroes.component.ts(27,5)中的错误:错误TS2322:类型   'Observable'不能分配给'Hero []'。属性   'Observable'类型中缺少'includes'。

我不确定我在这里做错了什么。我的英雄定义中没有'包含'属性。那个班级看起来像这个

export class Hero {
    id: number;
    name: string;
}

这是一个link to my project,虽然我不能让它在堆叠闪电战中运行

我会在这里列出完整的代码

heroes.component.ts

import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';

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

  constructor(private heroService: HeroService) { }

  selectedHero: Hero;

  heroes: Hero[];

  ngOnInit() {
    this.getHeroes();
  }

  onSelect(hero: Hero): void {
    this.selectedHero = hero;
  }

  getHeroes(): void {
    this.heroes = this.heroService.getHeroes();
  }




}

hero.service.ts

import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { Observable } from 'rxjs/Rx';
import { of } from 'rxjs/observable/of';

@Injectable()
export class HeroService {

  constructor() { }

  getHeroes(): Observable<Hero[]> {
    return of(HEROES);
  }
}

hero.ts

export class Hero {
    id: number;
    name: string;
}

模拟heroes.ts

import { Hero } from './hero';

export const HEROES: Hero[] = [
  { id: 11, name: 'Mr. Nice' },
  { id: 12, name: 'Narco' },
  { id: 13, name: 'Bombasto' },
  { id: 14, name: 'Celeritas' },
  { id: 15, name: 'Magneta' },
  { id: 16, name: 'RubberMan' },
  { id: 17, name: 'Dynama' },
  { id: 18, name: 'Dr IQ' },
  { id: 19, name: 'Magma' },
  { id: 20, name: 'Tornado' }
];

1 个答案:

答案 0 :(得分:4)

这是问题所在:

this.heroes

正如错误告诉您的那样,Hero[]的类型为Hero(因此,this.heroService.getHeroes();元素数组),而Observable<Hero[]>则返回可观察< / strong>,类型为getHeroes(): void { this.heroService.getHeroes().subscribe(result => this.heroes = result); }

由于您正在使用observable,因此您必须正确订阅它,如下所示:

{{1}}