#Tell http.get what really to expect

21 messages ยท Page 1 of 1 (latest)

sudden onyx
#

Hello there. I have this little snippet here:

getSomething(): String[] {
  return this.http.get(`some url`).pipe(retry(2), catchError(this.handleError))
}

The api endpoint is returning a string array but I get an error saying "Type Obervable<Object> is missing the following properties from type String[] ...."

Why is that? Or how to tell this get request that it is expecting an array not an object?

delicate stream
#

http.get parses the JSON body and returns that, but the compiler doesn't know what the JSON is going to look like. You can tell it exactly what to expect by adding a generic parameter like http.get<string[]>

sudden onyx
#

Alright, that makes sense. While the body is holding an array, the response still has the JSON type

#

Thanks

#

what if I want to return the value without needing to subscribe to this method? I tried to add map(res => res) to pipe but that still returns and observable. when I remove the Observeable from Observable<string[]> I get another error saying that "Type Observable<string[]> is missing the following properties from type string[]"

storm path
#

You can't really return a string array because it's not certain that the http request will return anything. It might error, which you should be prepared for.
It'll always return an observable.
I recommend looking into the options for get requests. By default a get request will be parsed to Observable<JSON> I believe. You can change this by passing a returntype in your get request options. But it will still be an observable.
That doesn't really matter though. Since in your subscription you can use the response as the returntype.
Recommend not piping/subscribing in your service. If you do it in components instead you can be sure there's no lingering subscriptions more easily.

#

I'll give you an example in a minute when I get to my computer.

sudden onyx
#

gotcha. so it might be possible but it's no good code

storm path
#

Pass the returntype in your get request, then use it in a subscription. That's the proper way. Not sure how useful it is for a string array.

storm path
#
    return this.httpClient.get(
      this.baseUrl + '/file_stream/image/thumbnail/' + uuid,
      { responseType: 'blob' }
    );```
Here's an example. It makes the responseType a blob.
In the screenshot you can see that it returns a blob in res.
sudden onyx
storm path
#

Webstorm from Jetbrains

sudden onyx
#

Ah, cool. Was just wondering because it shows the type without hovering over the value. Thanks for your help

slim kiln
#

VSC is miles better.

sudden onyx
ancient charm
storm path
#

It comes with the default Webstorm configuration, I believe. I haven't configured it much anyway.

ancient charm
#

Oh, sorry. I was thinking that was VSC.

slim kiln