我需要进行两次HTTP调用(第一次GET和第二次POST(,第二次基于第一次的结果。
以下是 GET 的响应:
{
"weekNbr": "34-2017",
"startDate": "2017-09-16",
"endDate": "2017-09-22"
}
然后,此响应将纵并作为 POST 请求发送,并使用以下 JSON:
{
"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 运算符可以做同样的事情,我们将不胜感激。
您可以使用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 => {});
我已经准备了这个虚拟服务:
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 可观察切换为虚拟of
可观察。
现场样品