-1

I have the following code:

getElements(apiUrl: string): Observable<Element[]> {
    return this.httpClient.get<any>(apiUrl + 'test/elements').pipe(
        catchError(error => {
            if(error.status === StatusCodes.NOT_FOUND){
                console.warn(error.status + ': no data found');
            }
            else {
                this.openModalError(error);
            }
            return throwError(() => error);
        })
    );
}

Depending on apiUrl, API will return either Element or Element[]. But I want my function to always return an array. How can I convert Element to an array when it isn't?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
BDM_45
  • 3
  • 1
  • A starting point would be telling the compiler "API will return either `Element` or `Element[]`", rather than that it could return `any`. – jonrsharpe Jun 23 '23 at 08:49

1 Answers1

3

It's only use rxjs/operator map to return if it's an array return the value, else create an array with an unique element. To know it we use the function isArray

return this.httpClient.get<Element[]>(apiUrl + 'test/elements').pipe(
     map((res:any)=>Array.isArray(res)?res:[res]),
     catchError...
})
Eliseo
  • 50,109
  • 4
  • 29
  • 67