在Angular中,可以使用RxJS的switchMap
操作符来处理嵌套的HTTP调用,而不使用success/failure块。下面是一个示例代码:
import { HttpClient } from '@angular/common/http';
import { switchMap } from 'rxjs/operators';
constructor(private http: HttpClient) {}
getData() {
this.http.get('api/firstEndpoint').pipe(
switchMap((response1: any) => {
// Process response1 if needed
// Make second HTTP call
return this.http.get('api/secondEndpoint');
}),
switchMap((response2: any) => {
// Process response2 if needed
// Make third HTTP call
return this.http.get('api/thirdEndpoint');
})
).subscribe((response3: any) => {
// Process final response3 if needed
});
}
在上面的示例中,我们使用switchMap
操作符来处理嵌套的HTTP调用。每个switchMap
操作符接收前一个HTTP调用的响应,并返回一个新的Observable,用于触发下一个HTTP调用。这样,我们可以避免使用success/failure块,而是将HTTP调用链接在一起。
请注意,在最后一个subscribe
中,我们可以处理最终的响应数据。如果需要,您可以在每个switchMap
中处理响应数据,或者在最后一个subscribe
中处理最终数据。