I want to have some clarifications and helps and about the master details Http calls in Angular2
I already read the answers for how to chain Http calls in Angular2.
How to chain Http calls in Angular2 http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http
In my case the issues are different. For instance I want to retrieve the details of a person inside the SWAPI API and display the details of that persons as well as the details about his movies. Bellow you have what I have done so far and it's not working.
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Response } from '@angular/http';
import { Http, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';
interface Film {
id: number;
title: string;
opening_crawl: string;
director: string;
producer: string;
}
interface Person {
id: number;
name: string;
mass: number;
height: number;
gender: string;
films: string[];
}
@Component({
selector: 'person-details',
template: '<h3>Details</h3><ul><li><b>Name : </b>{{person.name}} </li><li><b>Mass : </b> {{person.mass}} </li> <li><b>height :</b> {{person.height}} </li></ul>'
//displaying personnage films
})
export class PersonDetails2Component implements OnInit, OnDestroy {
person: Person;
sub: any;
filmdetails: any;
private baseUrl: string = 'http://swapi.co/api/people/1/';
constructor(private http: Http) {
console.log('PersonDetails2Component constructor');
}
ngOnInit() {
console.log('ngOnInit');
this.http.get(this.baseUrl, {headers: this.getHeaders()}).map((res: Response) => {
this.person = res.json().results.map(toPerson);
console.log('this.person');
return this.person;
})
.flatMap((person) => this.http.get(person.films[0])).map((res: Response) => res.json())
.subscribe(res => this.filmdetails = res);
}
ngOnDestroy() {
this.sub.unsubscribe();
}
private getHeaders() {
let headers = new Headers();
headers.append('Accept', 'application/json');
return headers;
}
}
function toPerson(r: any): Person {
let person = <Person>({
id: extractId(r),
name: r.name,
mass: r.mass,
height: r.height,
gender: r.gender,
films: r.films
});
console.log('person parsed =', person);
return person;
}
function extractId(personData: any) {
let extractedId = personData.url.replace('http://swapi.co/api/people/', '').replace('/', '');
return parseInt(extractedId);
}
Any help will be appreciated.