DEV Community

Lennart Johansson
Lennart Johansson

Posted on • Updated on

Calling a REST API with Angular 8

The Angular team is releasing new versions of their framework at a high pace. New features are presented with every release and I'm currently waiting for version 9 where the Ivy renderer will be included in new projects by default. In the meantime I want to write my first post here on DEV covering one of the most basic but fundamental things in programming. Making a REST call.

We will use a completely fresh Angular 8 install. You can either follow the instructions below or clone the repository with the end result.

First we install the Angular cli
sudo npm install -g @angular/cli

Then we make a new clean Angular app. You will be asked about routing and preferred styling. You can select no and css for the tutorial.
ng new angular-rest

ng new creates a standard Angular app with all the default configurations. We should now be able to see the example page by serving the app. Hopefully it looks like the screenshot below.

cd angular-rest
ng serve --open

Alt Text

We now need an API to call. For this tutorial I will be using Mocki to create a mock api. It's free and provides an easy way to quickly create a hosted mock api. Mocki gives you an url where there by default already is a Hello World response at the root. My url was
https://api.mocki.io/v1/ae70b3bc

Remember your URL for upcomming steps.

To make http calls with Angular we need to import the HttpClient in our app module angular-rest\src\app\app.module.ts. After adding it the file should look like this.

Alt Text

We can now inject the HttpClient in our future services. Services in Angular are used to call different parts of our REST API. We will create a service called HelloWorldService. Use the following angular cli command to create a service. The command will automatically create a services folder for us.

ng g s services/hello-world

The new service should look like this.

Alt Text

We will now modify it a bit by including the HttpClient and also adding our mock url from Mocki. It should look like this.

Alt Text

Finally we will modify our angular-rest\src\app\app.component.ts to use our service. We will use the service to make a getHelloWorldcall and log it to the console. Lets implement the changes and see if it works!

Alt Text

By checking the console in Chrome I can verify that we got a Hello World message! This was a super basic example of how to create a service in Angular 8 and use it to make a rest api call. If you want to read more about the HttpClient I recommend Angulars documentation. Please feel free to leave a comment if you have any questions.

Latest comments (0)