我必须进行多重同步网络通话,如果状态良好,则一个接一个地进行。
糟透了,但有效的代码:
this.api.post1().subscribe((data: any) => {
if (data.status== 'OK') {
this.api.post2().subscribe((data: any) => {
if (data.status== 'OK') {
this.api.post3().subscribe((data: any) => {
if (data.status== 'OK') {
this.api.post4().subscribe((data: any) => {
if (data.status == 'OK') {
// Do something
}else{
console.log('error: ' + data.status);
}
});
}else{
console.log('error: ' + data.status);
}
});
}else{
console.log('error: ' + data.status);
}
});
}else{
console.log('error: ' + data.status);
}
});
我尝试使用concatMap
const post1$ = this.api.post1();
const post2$ = this.api.post2();
const post3$ = this.api.post3();
const post4$ = this.api.post4();
from([post1$, post2$, post3$, post4$]).pipe(
concatMap(a => a)
).subscribe(res => console.log(res));
但是我需要检查一下每个答案是否都可以。有没有解决的办法?
这里是另一种方法:
import { concat, of } from 'rxjs';
import { concatMap, delay } from 'rxjs/operators';
var post1$ = of({status: "OK", data: 1});
var post2$ = of({status: "OK", data: 2});
var post3$ = of({status: "!OK", data: 3});
var post4$ = of({status: "OK", data: 4});
let index = -1;
let hasError = false;
var runSubscribe = data => {
if( hasError){
return;
}
index++;
if (data.status !== 'OK') {
console.log('error: ', data.status, data.data);
hasError = true;
return;
}
processData(index, data.data);
}
var processData = (index, data) => {
const random = Math.random()*100;
delay(random);
console.log(`${index} success:`, data, random);
}
concat(post1$, post2$, post3$, post4$).subscribe(runSubscribe);
由于其状态不是“ Ok”,它将停止在可观察到的第三位置。
如果其中任何一个错误如下所示,您可以从流中抛出一般错误。
const post1$ = this.api.post1();
const post2$ = this.api.post2();
const post3$ = this.api.post3();
const post4$ = this.api.post4();
concat([post1$, post2$, post3$, post4$]).pipe(
switchMap(data => {
if (data.status !== "OK") {
return throwError("Some error");
}
return of(data);
})
).subscribe(res => console.log(res));
OR:如果您需要了解有关每个可观察对象的特定信息,则可以使用concat,但是在到达concat之前,先将值通过每个端点传递。
const handleResponse = (type: string) =>
(responseObs) => responseObs.pipe(
switchMap(data => {
if (data.status !== "OK") {
return throwError("Some error about " + type);
}
return of(data);
})
);
const post1$ = this.api.post1().pipe(handleResponse("Post 1"));
const post2$ = this.api.post2().pipe(handleResponse("Post 2"));
const post3$ = this.api.post3().pipe(handleResponse("Post 3"));
const post4$ = this.api.post4().pipe(handleResponse("Post 4"));
concat([post1$, post2$, post3$, post4$]).subscribe(res => console.log(res));