我从angular tutorial学习angular4。 以下是从服务的功能中获取英雄的功能:
@Injectable()
export class HeroService {
getHeroes(): Promise<Hero[]> {
return new Promise(resolve => {
// Simulate server latency with 2 second delay
setTimeout(() => resolve(HEROES), 2000);
});
}
getHero(id: number): Promise<Hero> {
if (id < 0) {
throw new Error('Hero is not found.');
}
return this.getHeroes()
.then(heroes => heroes.find(hero => hero.id === id));
}
}
执行时会抛出错误:
TS2322: Type 'Promise<Hero | undefined>' is not assignable to type 'Promise<Hero>'.
Type 'Hero | undefined' is not assignable to type 'Hero'.
Type 'undefined' is not assignable to type 'Hero'.
还有其他人也遇到过这个问题吗?请帮忙。 谢谢。
@Component({
selector: 'hero-detail',
templateUrl: './hero-detail.component.html'
})
export class HeroDetailComponent implements OnInit {
@Input() hero: Hero;
constructor(private heroService: HeroService, private route: ActivatedRoute, private location: Location) { }
ngOnInit(): void {
this.route.paramMap
.switchMap((params: ParamMap) => this.heroService.getHero(+(params.get('id') || -1)))
.subscribe(hero => this.hero = hero);
}
goBack(): void {
this.location.back();
}
}
答案 0 :(得分:2)
由于所有元素都不符合条件 {{Array.find
将返回undefined
,因此打字错误的原因是1}}。
请参阅 doc ,了解hero.id === id
:
find()方法返回数组中第一个满足提供的测试函数的元素的值。 否则返回undefined。
为避免错误,您应将功能的返回类型更改为Array.find
。
Promise<Hero | undefined>