Skip to content

Instantly share code, notes, and snippets.

@killerchip
Created January 1, 2018 06:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save killerchip/3498804bbab1a1eaea7cdc0c864b6c4f to your computer and use it in GitHub Desktop.
Save killerchip/3498804bbab1a1eaea7cdc0c864b6c4f to your computer and use it in GitHub Desktop.
Angular Tip: Map HttpClient results to your model class

Map HttpClient results to model

When you use remote APIs, you might not have the model of the reponse JSON object, or it might not match to your app model. Don't be afraid to use map operator to transform the results.

Example

If you query https://jsonplaceholder.typicode.com/posts/ you will receive an array of articles. An article has the following format:

{
  userId: number,
  id: number,
  title: string,
  body: string
}

Your app model might be: article.model.ts

export class Article {

  constructor(
    public articleId: number,
    public articleSubject: string,
    public articleBody: string
  ){}

}

Then use map operator in the result to filter-out or transform object properties.

    this.httpClient.get('https://jsonplaceholder.typicode.com/posts/1')
      .pipe(
        map(
          data => { return new Article(
            data['id'],
            data['title'],
            data['body']
          );}
        )
      )
      .subscribe(
        data => console.log('data: ',data)
      );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment