Handling two different types of returns in one call (File(Blob) or JSON) Typscript

Viewed 121

This is kind of a confusing question, but hopefully someone can help.

Basically I am calling an API from a service in Angular 11 that can return one of two things.

  1. If the API processes the uploaded file correctly, it returns a new File to the user.
  2. If the API doesn't process the uploaded file correctly, it returns JSON to the user

How do I write a request that can handle either the response being a File or the response being JSON? I am having a ton of trouble with it.

Thanks in advance.

(My current request in my service)

return this._http.post(this.baseUrl, formData, {observe: 'response', responseType: 'blob'});
2 Answers

You should return with bad request from the server and you can use rxjs operators to solve this problem. Rxjs operators are used in pipe() function.

You can handle the bad request with catchError() operator https://www.learnrxjs.io/learn-rxjs/operators/error_handling/catch

In catchError() operator you should return with observable. In this example I just return with null value wrapped in observable.

return this._http.post(this.baseUrl, formData, {observe: 'response', responseType: 'blob'}).pipe(
  catchError((response: any) => {
    // you can write code here

    // you should return with observable
    return of(null);
  }),
);

Yo have to specify both types in the return type section of the method as shown below:

public apiCall(YourParameters): TypeA | TypeB {
  // your code
}
Related