Reputation: 437
i'm a beginner in TypeScript and Angular so this question might some strange. i have a simple JSON that returns a list of Heros: http://demo8521374.mockable.io/titan
i need my service to perform GetById but why Hero always comes out undefined, can someone please point me to the right location, this is what i'm doing:
return this.http.get("http://demo8521374.mockable.io/titan").map((response: Response) => {
var result = response.json().heroes as Hero[];
console.log(result);
return result;
}).filter(x => x.filter(x => x.id == id)).first().toPromise();
in my console i can see the array was printed but in my component is not getting the object:
ngOnInit(): void {
this.route.paramMap
.switchMap((params: ParamMap) => this.heroService.getHero(+params.get('id')))
.subscribe(hero => this.hero = hero);
console.log(this.hero)
}
Thanks!
Upvotes: 1
Views: 525
Reputation: 437
modified the code as follow and it worked, sure there is a better way:
getHero(id: number): Promise<Hero> {
return this.http.get("http://demo8521374.mockable.io/titan").map((response: Response) => {
var result = response.json().heroes as Hero[];
console.log(result);
return result;
})
.map(heros => {
let y = heros.filter(x => x.id == id)[0]
console.log(y);
return y;
})
.toPromise();
Upvotes: 1
Reputation: 11474
While switchMap
returns a new observable, I assume the getHero
method returns an observable as well. In that case you need to subscribe to the getHero
observable and now the switchMap
observable to assign to your hero property as follows:
ngOnInit(): void {
this.route.paramMap
.switchMap((params: ParamMap) => this.heroService.getHero(+params.get('id'))
.subscribe(hero => this.hero = hero));
console.log(this.hero)
}
Or if getHero
is returning a promise, then it should look as follows:
ngOnInit(): void {
this.route.paramMap
.do((params: ParamMap) => this.heroService.getHero(+params.get('id'))
.then(hero => this.hero = hero)).subscribe();
console.log(this.hero)
}
It is hard to proscribe an answer to this question though as what you are doing is a little unclear and seems to indicate that you are mixing Observables and Promises when my guess is that you only need Observables.
Update service to:
return this.http.get("http://demo8521374.mockable.io/titan").map((response: Response) => {
var result = response.json().heroes as Hero[];
console.log(result);
return result;
}).filter(x => x.id === id).first().toPromise();
Upvotes: 0