【发布时间】:2019-08-06 22:55:04
【问题描述】:
以下代码来自https://angular.io/tutorial/toh-pt6。 .tap 会引发编译错误,但没有它,代码也能正常工作。
hero.service.ts:
getHeroes(): Observable<Hero[]> {
return this.httpClient.get<Hero[]>(this.heroesUrl)
.pipe(
tap(_ => this.log('fetched heroes')), //It works without this line
catchError( this.handleError<Hero[]>('getHeroes', []) )
);
}
in-memory-data.service.ts:这会模拟 httpClient.get 上的响应
export class InMemoryDataService implements InMemoryDbService {
constructor() {
}
createDb() {
const heroes = [
{ id: 11, name: 'Dr 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' }
];
return {heroes};
}
}
我收到以下编译错误:
Type 'Observable<{} | Hero[]>' is not assignable to type 'Observable<Hero[]>'.
Type '{} | Hero[]' is not assignable to type 'Hero[]'.
Type '{}' is not assignable to type 'Hero[]'.
Property 'length' is missing in type '{}'. [2322]
看起来返回的对象是 {Hero[]},而它只需要一个数组 Hero[]。 我试图修复它,
createDb() {
const heroes: Hero[] = [
{id: 11, name: 'Dr Nice'},
...
];
return heroes;
}
但 createDb() 返回类型是 Observable{}。这引出了以下问题:
- 如果不匹配,如果没有 .tap 行,它是如何工作的?
- 如何解决?
谢谢。
【问题讨论】: