我希望得到一些澄清和帮助,以及Http在Angular2中调用的主要细节
我已经阅读了如何在Angular2中链接Http调用的答案。
How to chain Http calls in Angular2 http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http
就我而言,问题是不同的。例如,我想在SWAPI API中检索一个人的详细信息,并显示这些人的详细信息以及有关他的电影的详细信息。贝娄你有我到目前为止所做的事情而且它没有用。
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);
}
任何帮助将不胜感激。