user1604066
user1604066

Reputation: 3

Angular 6 Nested HTTP Calls Nested Call Never Executes

Working in Angular 6 I have two HTTP calls that need to execute in series. The first call succeeds and the second call indicates success but never actually makes an HTTP request.

If I break up the two calls and execute them individually they both work. However, when combining them in series the second call never works.

The general idea here is to request a signed URL from the server and upon receipt upload a file to the specified URL.

export class StaticAssetService {
  constructor(private httpClient: HttpClient) { }

  public uploadAsset(assetType: StaticAssetType, file: File): Observable<any> {
    if (file) {
      return this.httpClient.get(`${environment.apiURI}/secure/file-upload/getPresignedURLForUpload.json`, {
        params: {
          assetType: assetType,
          originalFileName: file.name
        }
      }).pipe(map(response => {
        return this.httpClient.put(response.signedURL, file, {
          headers: new HttpHeaders({'Content-Type': file.type}),
          reportProgress: true
        })
      }));
    }
  }
}

Upvotes: 0

Views: 1020

Answers (1)

DeborahK
DeborahK

Reputation: 60596

Nesting HTTP calls using the syntax shown above is not recommended practice. Rather, there are specific RxJS operators (similar to map) that are specifically for executing HTTP calls in series.

The switchMap recommended by the commenter is one of those operators. Here is an example:

Angular4 - Nested Http Calls

Here are some articles that may be helpful:

https://medium.com/@juliapassynkova/switchmap-in-details-b98d34145311

https://blog.angular-university.io/rxjs-higher-order-mapping/

Upvotes: 1

Related Questions