我正在阅读 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/