javascript - 如何使用 Rxjs First() 运算符仅获取一个项目

标签 javascript angular typescript rxjs

我正在阅读 Routing and navigation在 Angular 。 first() rxjs 的运算符不起作用,并且出现错误。

这是我的服务:

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { first } from 'rxjs/operators';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';

@Injectable({
  providedIn: 'root',
})
export class HeroService {
  constructor() { }

  getHeroes(): Observable<Hero[]> {
    return of(HEROES);
  }

  getHero(id: string): Observable<Hero> {
    // With the following code I get error
    return this.getHeroes().pipe(
      first(hero => hero.id === +id)
    );
  }
}

这是我的英雄:

export interface Hero {
  id: number;
  name: string;
}

这是我的模拟英雄:

import { Hero } from './hero';

export const HEROES: Hero[] = [
  { 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' }
];

这是我的错误:

Type 'Observable<Hero | Hero[]>' is not assignable to type 'Observable<Hero>'. Type 'Hero | Hero[]' is not assignable to type 'Hero'. Type 'Hero[]' is missing the following properties from type 'Hero': id, name

我想要的是只获得具有我想要的 id 的英雄;我该怎么做?

最佳答案

原因是您正在使用 of而不是from函数创建 getHeroes() 返回的 Observable方法。

如果您像这样更改代码,则不会再出现编译错误

getHeroes(): Observable<Hero> {  // the returned Observable emits Hero and not Hero[]
    return from(HEROES);   // from rather thanof
  }

  getHero(id: string): Observable<Hero> {
    return this.getHeroes().pipe(
      first(hero => hero.id === +id)
    );
  }

通过此更改,getHeroes()发出 Hero 的流s 以及您传递给 first 的谓词函数仅收到 1 Hero当时并不是 Hero 的数组s。

如果您想维护getHeroes()的原始版本比你必须改变getHero()像这样

getHero(id: string): Observable<Hero> {
  return getHeroes().pipe(
    map(heroes => heroes.find(hero => hero.id === +id))
  );
}

关于javascript - 如何使用 Rxjs First() 运算符仅获取一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60971249/

相关文章:

javascript - 类型上不存在属性(编辑器内部)

javascript - 同步两个对象并应用新值

javascript - 使用 Chosen 插件更改选择中的选择

javascript - 重新启动我的绘图功能不起作用

angular - 无法解码下载的字体,使用 nginx 部署 Angular 6 应用程序时出现 OTS 解析错误

angular - 将angular2中管道的输出分配给变量

typescript - 当启用标志 --strictNullChecks 时,null 不可分配给 void

typescript - IE 11 - 抛出 'webpackJsonp' 未定义

javascript - 更改 Django 中多条形图的颜色

angular - 在Angular 2模板文字中检测变量的使用