角形RxJS管道龙头

时间:2019-08-06 22:55:04

标签: angular rxjs

以下代码来自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 {}。提出以下问题:

  1. 如果不匹配,没有.tap行怎么办?
  2. 如何解决?

谢谢。

2 个答案:

答案 0 :(得分:0)

在in-memory-data.service.ts中,您试图返回对象内部的数组。这是您遇到编译错误的问题。

尝试使用return {heroes}代替return heroes

答案 1 :(得分:0)

我在hero.service.ts中有import语句,

import { catchError } from 'rxjs/operators';

只需要

import { catchError, tap } from 'rxjs/operators';

抛出的编译错误非常容易引起误解。