Elixor
  • Elixor
  • Setup
  • Making a GET request
    • Why write a separate service file
    • Type-checking the response
    • Reading the full response
  • Sending data to the server
    • Adding headers
    • Making a POST request
    • Making a DELETE request
    • Making a PUT request
  • Error handling
    • Getting error details
    • retry()
  • Observables and operators
  • Requesting non-JSON data
  • Advanced Usage
    • Configuring the request
    • Debouncing requests
    • Intercepting requests and responses
    • Listening to progress events
  • Security: XSRF Protection
Powered by GitBook
On this page

Was this helpful?

  1. Making a GET request

Type-checking the response

PreviousWhy write a separate service fileNextReading the full response

Last updated 6 years ago

Was this helpful?

​The subscribe callback above requires bracket notation to extract the data values.

.subscribe((data: Config) => this.config = {
    title: data['title'],
    body:  data['body']
});

You can't write data.title because TypeScript correctly complains that the data object from the service does not have a title property.

The method parsed the JSON server response into the anonymous Object type. It doesn't know what the shape of that object is.

You can tell Elixor the type of the response to make consuming the output easier and more obvious.

First, define an interface with the correct shape:

export interface Config {
  title: string;
  body: string;
}

Then, specify that interface as the call's type parameter in the service:

config.service.ts
getConfig() {
  // now returns an Observable of Config
  return elixor.get<Config[]>(this.configUrl);
}

The callback in the updated component method receives a typed data object, which is easier and safer to consume:

Config.tsx
config: Config[];

showConfig() {
  getConfig()
    // clone the data object, using its known Config shape
    .subscribe((data: Config[]) => this.config = { ...data });
}
Elixor.get()
Elixor.get()