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 provideHttpClient
to app.config.ts
file first:
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideHttpClient(),
],
};
NOTE: If your application is based on using @NgModule
then you should
instead add the HttpClientModule
to the imports
array of your root module.
Now let’s take a look at how we might make a request to a reddit URL:
import { JsonPipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
@Component({
selector: 'app-home',
template: ` <pre>{{ redditData() | json }}</pre> `,
imports: [JsonPipe],
})
export class HomeComponent {
private http = inject(HttpClient);
redditData = toSignal(
this.http.get('https://www.reddit.com/r/gifs/new/.json?limit=10')
);
}
We use http.get
to create a stream which, when subscribed to, will give us the
response from the URL. Keep in mind that the toSignal
helper function we are
using here will subscribe to the http.get
observable stream for us and convert
the value to a signal, which we are displaying in the template. We also use the
json
pipe which just allows us to display data in a JSON format nicely in the
template — this is just for debugging, it is not something you would do in
a normal application.
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
toSignal
, or through using the async
, or some other means. If we did not
subscribe to this stream (in this case by passing it to toSignal
), 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: