大家好我刚刚创建了一个简单的ajax调用,其中第一个ajax调用的响应用于第二个ajax调用,所以我在angular 2中使用flatmap来运行第一个ajax调用并在第二个ajax调用中使用它的响应这里是代码但只有第一个ajax调用正常工作,似乎.flatmap之后的代码没有运行。请帮我解决这个问题。
createPerson(personClass: User, addressClass: Address): Rx.Observable <string> {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append("Cache-Control", "no-cache");
headers.append("Cache-Control", "no-store");
headers.append("If-Modified-Since", "Mon, 26 Jul 1997 05:00:00 GMT");
var myObj = {
"firstName": personClass.firstname,
"age": personClass.age,
"lastName": personClass.lastname,
"dateOfBirth": "null"
};
return this.http.post(`${webServiceEndpoint}/person`, JSON.stringify(myObj), {
headers: headers
}).map((res: Response) => res.json())
.flatMap(data => {
let body = data.json();
console.log(body);
var myObj2 = {
"personId": body,
"address1": addressClass.streetname,
"city": addressClass.city,
"zipCode": addressClass.zipcode
};
return this.http.post(`${webServiceEndpoint}/address`, JSON.stringify(myObj2), {
headers: headers
}).map((res1: Response) => res1.json())
})
}
&#13;
答案 0 :(得分:0)
由于data
不是Response
对象,因此可能会失败:
let body = data.json();
答案 1 :(得分:0)
我认为你以错误的方式使用RxJS(你不会认为是被动的)(如果你可以使用最新版本的角度):
示例(非常简洁的方法,您可以非常轻松地测试代码):
createPerson(personClass: User, addressClass: Address): Observable<Address> {
/* Angular 5 you can do this into the HttpClient Interceptor */
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append("Cache-Control", "no-cache");
headers.append("Cache-Control", "no-store");
headers.append("If-Modified-Since", "Mon, 26 Jul 1997 05:00:00 GMT");
return this.createPerson(person)
.switchMap((person: Person) => this.http.post<Person>(`${webServiceEndpoint}/person`, { person , headers})
.switchMap((person: Person) => createAddress(person, address))
.switchMap((person: Person) => this.http.post(`${webServiceEndpoint}/address`, person, {
headers: headers
}));
}
createAddress(person: Person, address: Address): Observable<Address> {
return Observable.of({
"personId": person.id,
"address1": addressClass.streetname,
"city": addressClass.city,
"zipCode": addressClass.zipcode
});
}
createPerson(person: Person): Observable<Person> {
return Observable.of(<Person>{
"firstName": personClass.firstname,
"age": personClass.age,
"lastName": personClass.lastname,
"dateOfBirth": "null"
});
}