【问题标题】:Angular RxJS pipe tapAngular RxJS 水龙头
【发布时间】: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{}。这引出了以下问题:

  1. 如果不匹配,如果没有 .tap 行,它是如何工作的?
  2. 如何解决?

谢谢。

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

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

    import { catchError } from 'rxjs/operators';
    

    只需要,

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

    抛出的编译错误非常具有误导性。

    【讨论】:

      【解决方案2】:

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

      试试return heroes,而不是return {heroes}

      【讨论】:

      • 我已经在帖子中提到我已经尝试过了,我得到了同样的错误。
      • 我认为 Bayramali 所写的内容是正确的;您尚未在 createDb() 上定义返回类型,执行 createDb: Observable&lt;Hero[]&gt; 会给您带来其他编译错误,因为返回的类型与预期的返回类型不匹配。明确这一点可以提高代码的类型检查和可读性。
      • 我同意代码可以更好。我把它留在官方教程中,所以很容易理解。方法签名是''''abstract createDb(reqInfo?:RequestInfo): {} |可观察 |承诺;''''。我无法改变这一点。
      猜你喜欢
      • 2019-06-30
      • 1970-01-01
      • 2021-12-14
      • 2014-10-04
      • 2022-10-06
      • 2013-04-10
      • 2011-02-11
      • 2011-07-06
      • 2021-10-17
      相关资源
      最近更新 更多