我需要进行一系列的http调用,其中每个调用都取决于之前的响应(主体或标题)。我如何用Observables实现这一目标?
到目前为止,我已经制作了丑陋的嵌套订阅:
this.http.get(url1)
.subscribe(response1 => {
const params1 = something(response1);
this.http.post(url2, params1)
.subscribe(response2 => {
const params2 = something(response1,response2);
this.http.post(url3, params2)
.subscribe(response3 => {
const params3 = something(response1,response2,response3);
this.http.post(url4, params3)
.subscribe(response4 => {
const params4 = something(response1,response2,response3,response4);
this.http.post(url5, params4)
.subscribe(response5 => console.log(response5));
});
});
});
});
您可以尝试使用flatmap rxJS运算符以获得更好的可读性。我认为它看起来像下面这样。 rxJS6,您需要使用管道运算符才能工作。
更简单的例子
这是一个更成熟的示例解决方案,以了解最新情况。
public test(): Observable<any>
{
return of([1]);
//when subscribed to returns [1]
}
public testTwo(value): void
{
console.log(value); // [1] <- comes from the observable
this.fromEndpoint = value;
}
public testThree(example): Observable<any>
{
if (example[0] === 1)
{
return of([3]);
// return an array of [3] when subscribed to.
}
}
public ngOnInit()
{
this.test().pipe(flatMap(response1 => (this.testTwo(response1),
this.testThree(response1)))).subscribe(final =>
{
console.log(final);
// this logs ['3'] as the calls are chained with flatMap
});
}
我希望我把更简单的例子放在一起会让它更容易理解。这使我认为您可以为您提供的代码执行以下操作。
解
this.http.get(url1).pipe(
flatMap(response1 => (this.exampleFunction(response1), this.http.get(response1))),
flatMap(response2 => (this.responseValue = response2, this.http.get(response2))),
flatMap(response3 => (this.exampleFunctionThree(response3), this.http.get(response3)))
).subscribe(final => {
console.log(final);
console.log(this.responseValue);
});
请注意,console.log(final);
将仅记录最后一次observable / api调用的结果,并且不会沿途收集值。如果您需要收集所有值,您可以传入一个单独的函数来发送响应,或者在更高的范围内声明它。我在上面的例子中已经证明了这一点。
文档