-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?

1
  • A starting point would be telling the compiler "API will return either Element or Element[]", rather than that it could return any. Commented Jun 23, 2023 at 8:49

1 Answer 1

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...
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.