Type-checking the response

​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 Elixor.get() 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 Elixor.get() 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 });
}

Last updated