Angular HTTP & Get Requests Tutorial

In this Angular tutorial we learn how to fetch (get) data from an external resource, like a database.

We cover the Publish & Subscribe model and how to use returned responses with Observables.

What is the Http mechanism

The HttpClient Module allows us to fetch data from an external source, like a database.

It requires us to Subscribe to the returned response by using an Observable .

Lesson project setup

For this lesson there is no initial setup other than having an app.

To keep things simple, we will be working directly from inside the main ‘app.component’ component and will create whatever else we need on a step-by-step basis.

How to fetch data using the Http mechanism

From Angular version 5, we use the HttpClient module. This new module provides a simplified API for HTTP functionality.

1. As the first step, let’s go ahead and import the module so that we can work with it.

The module is called ‘HttpClientModule’ and is available from ‘@angular/common/http’.

We also need to add it to the imports array so that it’s available within the App module.

By importing the HttpClientModule, we are also registering the Http service with Angular’s injector. We don’t have to explicitly register it in the providers metadata.

Example: app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent  } from './app.component';

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

2. The next step is to create a service from where we can make an HTTP Get request.

We will use the CLI to generate a new service and call it ‘employee’.

Example: CLI Command
ng generate service employee

To use HTTP in our new sevice, we declare it as a dependency in the constructor and import it at the top of the document.

Example: employee.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  constructor(private http: HttpClient) { }
}

Now we have the http local object to refer to the instance of HttpClient and we are ready to make a Get request.

To make a get request, we use the get() method which takes a URL to the file or external resource we want to bring in.

3. Because we don’t have an actual web server, we will create and use a local file for the demonstration that we will pretend is on a web server.

Inside the project folder, navigate into the src > app > assets directory and create a new folder called ‘data’.

In the data folder create a new file called employees.json .

Example:
├───src
│   ├───app
│   |   ├───assets
│   │   |   ├───data
│   │   |   |   └───employees.json

Now copy & paste the following into the employees.json file.

Example: employees.json
[
  { "id": 1, "name": "John" },
  { "id": 2, "name": "Jane" },
  { "id": 3, "name": "Jack" },
  { "id": 4, "name": "Jill" }
]

This represents data we would get from an external resource, like MongoDB.

4. As mentioned before, we use the get() method to bring in the data.

This method takes the URL to the external resource as its argument. Because we are using a local resource, we will simply specify the path to it.

Example: employee.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  constructor(private http: HttpClient) { }

  getEmployees() {
    return this.http.get('../assets/data/employees.json');
  }
}

If you have a web server, you can simply replace the URL in the method above to point to that resource. The application will still work as expected.

5. Our next step is to cast (convert) the Observable, that the get() method returns, into a format that represents an array of employees.

For that, we will create and use a custom employee type. In the app folder, create a new file called employee.ts .

In this new file, create an interface called IEmployee with the id and name properties.

Example: employee.ts
export interface IEmployee {
  id: number,
  name: string
}

We now have an employee type that the Observable can be cast into.

6. Next, we need to specify that the getEmployees() method will return an observable of type IEmployee array.

We also need to add the IEmployee array type to the get() request.

Remember to import the IEmployee interface, and the Observable module at the top of the document.

Example: employee.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { IEmployee } from './employee';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  constructor(private http: HttpClient) { }

  getEmployees(): Observable<IEmployee[]> {

    return this.http.get<IEmployee[]>('../assets/data/employees.json');
  }
}

7. Now we need to Subscribe to that observable from the component we want to use it in.

In our case we can simply use the main ‘app’ component for demonstration.

First, let’s import and inject our EmployeeService into the component.

Example: app.component.ts
import { Component } from '@angular/core';
import { EmployeeService } from './employee.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {

  constructor(private empService: EmployeeService) { }
}

Now we need to subscribe to the Observable that’s returned from the getEmployees() method, and store the data it returns in a local array called ‘employees’.

Example: app.component.ts
import { Component } from '@angular/core';
import { EmployeeService } from './employee.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {

  public employees:any = [];

  constructor(private empService: EmployeeService) { }

  ngOnInit(): void {
    this.empService.getEmployees().subscribe(
      data => {
        this.employees = data;
      }
    );
  }
}

We can work on this data further, or display it to the user.

8. Let’s display the data in the main ‘app’ component’s view with a simple ngFor directive.

Example: app.component.html
<ul *ngFor="let employee of employees">
  <li>{{ employee.id }}: {{ employee.name }}</li>
</ul>

In the example above, we loop through the array and access each employee’s Id and Name through dot notation.

Output: app.component.html
1: John
2: Jane
3: Jack
4: Jill