我需要进行两个HTTP调用(第一个GET和第二个POST),第二个基于第一个的结果。
这是GET的回复:
{
"weekNbr": "34-2017",
"startDate": "2017-09-16",
"endDate": "2017-09-22"
}
然后将处理此响应,并将其作为带有以下JSON的POST请求发送:
{
"weekNbr": 34, (as received above)
"year": 2017 (as received above)
}
一种解决方案:
http.get(url1).pipe(
map(do your maipulation)
).subscribe(
(newlyCreatedObject) => {
return http.post(url2,newlyCreatedObject);
}
);
但是我认为这不是正确的方法。
注意: 这些调用应该在单个服务中进行。如果有任何rxjs运算符可以执行相同的操作,将不胜感激。
答案 0 :(得分:4)
您可以使用flatMap/mergeMap
运算符发出两个HTTP请求,一个取决于另一个。
赞:
http.get(data).flatMap(res => {
// res is response of Get
// manipulate the data and passed in post call
return http.post(data);
})
.map(res => {})
.catch(e => {});
答案 1 :(得分:0)
我已经准备好这项虚拟服务:
import {of, Observable} from 'rxjs';
import {flatMap} from 'rxjs/operators';
/**
* Dummy get observable.
*/
export class MyService {
getInformation$(): Observable<{foo:string}> {
return of({foo:'bar'});
}
postInformation$(params:{foo:string}): Observable<any> {
return of({
fooUpperCase: params.foo.toUpperCase() // Stupid transformation for demonstration only
});
}
main() {
this.getInformation$().pipe(
flatMap(data => this.postInformation$(data)) // receive each next and return new observable.
).subscribe(console.log);
}
}
new MyService().main();
仅出于演示目的,我将http observable切换为哑of
可观察。