【发布时间】:2019-09-26 12:12:47
【问题描述】:
我正在学习官方 Angular 教程 (https://angular.io/tutorial/toh-pt4)。对不起我的水平低:(
我正在尝试修改一个返回英雄列表的服务...作为 rxjs 的 observables 对象,因为这是最有效的方法
hero.service.ts
==============
import {Injectable} from '@ angular / core';
import {Observable, of} from 'rxjs';
import {Hero} from './hero';
import {HEROES} from './mock-heroes';
import {MessageService} from './message.service';
@Injectable ({
providedIn: 'root',
})
export class HeroService {
constructor (private messageService: MessageService) {}
getHeroes (): Observable <Hero []> {
// TODO: send the message _after_ fetching the heroes
this.messageService.add ('HeroService: fetched heroes');
return of (HEROES);
}
}
mock-heroes
===========
import {Hero} from './hero';
export const HEROES: Hero [] = [
{id: 11, name: 'Mr. Nice '},
{id: 12, name: 'Narco'},
{id: 13, name: 'Bombast'},
{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'}
];
我想要一个服务,当我传递一个 id 时只返回一个英雄
import {Injectable} from '@ angular / core';
import {Hero} from './hero';
import {HEROES} from './mock-heroes';
import {Observable, of} from 'rxjs';
import {MessageService} from './message.service';
import {map} from 'rxjs / operators';
@Injectable ({
providedIn: 'root'
})
export class HeroService {
private heroes: Observable <Hero []>;
getHeroes (): Observable <Hero []> {
this.messageService.add ('HeroService: fetched heroes');
// return of (HEROES);
this.heroes = of (HEROES);
return this.heroes;
}
getHeroeById (id: number): Observable <Hero> {
this.messageService.add ('A hero is queried with id' + id);
return this.heroes.pipe (map (x => x.id === id));
}
constructor (private messageService: MessageService) {}
/ * getHeroes (): Hero [] {
return HEROES;
} * /
//builder() { }
}
src / app / hero.service.ts (26,5) 中的错误:错误 TS2322:类型“Observable”不可分配给类型“Observable”。 类型“布尔”不能分配给类型“英雄”。 src/app/hero.service.ts (26.40): TS2339 错误: 属性 'id' 在类型'Hero []' 上不存在。
你能帮帮我吗?
【问题讨论】: