I am currently studying angular4 using the angular tutorial. Here is a function to retrieve a hero from a service:
@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 not found.');
}
return this.getHeroes()
.then(heroes => heroes.find(hero => hero.id === id));
}
}
Upon execution, it generates an error:
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'.
Has anyone else encountered this issue? Any assistance would be greatly appreciated. Thank you.
@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();
}
}