3d cartoon hands holding a phone

Unlock full course by purchasing a membership

Lesson 11

Fetching Data from a Backend/API

Pulling data from an external source into your application

STANDARD

Fetching Data from a Backend/API

In the previous lessons, we have seen glimpses of using the HttpClient to fetch data from a server. Now we are going to look at it in detail. This is a key part of building an application because it is what allows you to reach outside of your application and pull data in from some external source (as well as send data back to it).

Some applications may be entirely self contained, but many need to integrate with some kind of backend. As you will see, the type of backend does not particularly matter. It could be written in Java, Go, Rust, PHP, Node. It could use MySQL, PostgreSQL, a static JSON file, CouchDB, Redis, MongoDB or just about anything else. The general idea is that we will make a request to some external server, and it will send a response back to our application with the data we need.

A Simple Example

A lot of the time, we will get data back from servers in a JSON format. If you don’t already know what that is it would be worth doing some research, but the basic idea is that it is a string that represents data in the form of a JavaScript object (JSON stands for JavaScript Object Notation). That JSON response can then be converted into a real JavaScript object in our application.

A low friction way to experiment with pulling data into your application is to use the Reddit API. The great thing about the Reddit API is that it is publicly accessible and doesn’t require any kind of authorisation to access.

You can create a JSON feed of posts from subreddits simply by visiting a URL in the following format:

If you click on that link, you will see a JSON feed containing 10 submissions from the gifs subreddit, sorted by the hot filter. But… how do we get that JSON data from that URL into our Angular application?

The answer is to use the HttpClient service which is provided by Angular and allows you to make HTTP requests. If you’re not familiar with what an HTTP request is, basically every time your browser tries to load anything (a document, image, a file etc.) it sends an HTTP request to do that. We can make an HTTP request to a page that spits out some JSON data, and pull that into our application.

Let’s do that now, but remember if you are following along that you will need to add the HttpClientModule to your root module first. Now let’s take a look at how we might make a request to a reddit URL:

import { CommonModule } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { ChangeDetectionStrategy, Component, NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

@Component({
  selector: 'app-home',
  template: `
    <pre *ngIf="redditData$ | async as data">{{ data | json }}</pre>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class HomeComponent {
  redditData$ = this.http.get(
    'https://www.reddit.com/r/gifs/new/.json?limit=10'
  );

  constructor(private http: HttpClient) {}
}

We use http.get to create a stream which, when subscribed to, will give us the response from the address. We are using the reactive approach here - rather than manually subscribing to http.get in ngOnInit we are instead subscribing to it with the async pipe in the template. This allows us to pull the result out of the stream, and then we are displaying it using the json pipe (this pipe just allows us to display data in a JSON format more nicely in a template).

NOTE: An observable stream like the one from http.get() won’t actually be executed until it is subscribed to - either manually or through using the async pipe as we are doing above. If we did not subscribe to this stream, you would see that no network request is made.

We still haven’t got to discussing observable streams and reactive programming in detail yet, so I don’t want to go off topic here. However, I think it is useful to see a more practical case here. We don’t want to just display JSON in our application, we probably want to do something like display a list using this data.

This is how you could do that:

import { CommonModule } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { ChangeDetectionStrategy, Component, NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { map } from 'rxjs';

@Component({
  selector: 'app-home',
  template: `
    <ul *ngIf="redditData$ | async as posts">
      <li *ngFor="let post of posts">
        {{ post.data.title }}
      </li>
    </ul>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class HomeComponent {
  redditData$ = this.http
    .get('https://www.reddit.com/r/gifs/new/.json?limit=10')
    .pipe(map((res: any) => res.data.children));

  constructor(private http: HttpClient) {}
}
STANDARD
Key

Thanks for checking out the preview of this lesson!

You do not have the appropriate membership to view the full lesson. If you would like full access to this module you can view membership options (or log in if you are already have an appropriate membership).