我正在跟踪英雄之旅教程,现在我正在尝试将可观测数据集成到我的项目中。将我的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);
}
}我没有收到以下错误
组件(27,5):错误TS2322:类型'Hero[]‘不能指定为’Hero[]‘。属性“包括”在“可观察”类型中缺失。
我不太清楚我在这里做错了什么。在我的英雄定义上,我并没有真正的“包括”属性。那堂课看上去像这样
export class Hero {
id: number;
name: string;
}这是一个链接到我的项目,尽管我无法让它在堆栈闪电战中运行
我会在这里列出全部代码
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;
}mock-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' }
];发布于 2018-05-07 13:40:05
这就是问题所在:
getHeroes(): void {
this.heroes = this.heroService.getHeroes();
}正如错误告诉您的那样,this.heroes的类型是Hero[] (因此是Hero元素的数组),而this.heroService.getHeroes();则返回一个可观察的,该的类型是Observable<Hero[]>。
由于您使用的是一个可观察的,因此您必须正确地订阅它,如下所示:
getHeroes(): void {
this.heroService.getHeroes().subscribe(result => this.heroes = result);
}https://stackoverflow.com/questions/50215571
复制相似问题