Angular 6 Http Get Example

In this tutorial, we will see Angular 6 Http Get Example. Most modern front-end applications communicate with backend services over the HTTP protocol. They communicate via an API. The HttpClient in @angular/common/http offers a simplified client HTTP API for Angular applications that rests on the XMLHttpRequest interface.

For this example, we will create a backend JSON server. Then Angular 6 application will send a network request to JSON Server and then get a response from the server and display the data on the frontend. We use HttpClient API provided by Angular CLI

Now, we start our Angular 6 HTTP Get Example Tutorial by installing Angular 6 on our local machine.

Angular 6 Http Get Example

We install Angular via Angular CLI.

#1: Install Angular 6 project.

If you have not installed Angular CLI globally on your machine, then install it using the following command.

npm install -g @angular/cli

# or

yarn add global @angular/cli

Now, create a local project using the following command.

ng new ng6http

Now, start the application using the following command.

ng serve --open

#2: Create a JSON server.

For getting JSON response from an API, we do need a server.  To create a server, right now, there are lots of packages are available. We use json-server package. So let us install that package.

yarn global add json-server

# or

npm install -g json-server

Now we need to create a folder inside src directory called data and in that folder, create one file called db.json. Let us add the following data inside a db.json file.

{
    "books": [
    {
        "id": "1",
        "name": "A song of ice and fire",
        "author": "George RR Martin"
    },
    {
        "id": "2",
        "name": "Harry Potter",
        "author": "JK Rowling"
    },
    {
        "id": "3",
        "name": "Anna Karenina",
        "author": "Leo Tolstoy"
    },
    {
        "id": "4",
        "name": "Great Expectations",
        "author": "Charles Dickens"
    },
    {
        "id": "5",
        "name": "Middlemarch",
        "author": "George Eliot"
    }]
}

Now, we need to start a JSON server that serves this data. So go to the terminal and type the following command.

json-server --watch src/data/db.json --port 4000

Now, you can access all the books on this URL: http://localhost:4000/books

#3: Setup HttpClient.

Now, Angular comes with HttpClient Module, so we just need to register inside our application. So open the app.module.ts file and write the following code.

// app.module.ts

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

imports: [
    BrowserModule,
    HttpClientModule
  ],

#4: Define our Book.ts model.

We have created the JSON server, so we know that what kind of data backend will serve to our application.

So, we will create one interface on the Angular application that has all the datatypes of our backend.

It is kind of modeling of our data; we define the schema of the backend data at frontend.

Inside app folder, create one file called Book.ts.

// Book.ts

export interface Book {
    id: Number;
    name: String;
    author: String;
}

So, we get the data of Books, and its datatype is array, but its properties datatypes are Number and String.

What I am trying to say is that, from the JSON server, we are expecting an array of Books

The books are consist of different properties. Those properties datatypes are defined as above in the interface.

#5: Make a service that communicates to the server.

Now, inside app folder, we need to create one service file that talks to the server and fetch the data from an API. So type the following command to generate the service file.

ng g s book --spec false

Now, import this service inside app.module.ts file.

// app.module.ts

import { BookService } from './book.service';

providers: [BookService],

Next step is to write the code that sends the GET request to the server and fetch the data.

// book.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

  url = 'http://localhost:4000';
  constructor(private http: HttpClient) { }

  getBooks() {
    return this
            .http
            .get(`${this.url}/books`);
        }
}

#6: Create a table that displays the data.

Now, inside app.component.ts file, we need to add the code that calls the service’s function.

// app.component.ts

import { Component , OnInit} from '@angular/core';
import { BookService } from './book.service';
import { Book } from './Book';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  books: Book[];

  constructor(private bookService: BookService) { }

  ngOnInit() {
    this
      .bookService
      .getBooks()
      .subscribe((data: Book[]) => {
        this.books = data;
    });
  }
}

Now, finally code the HTML file that displays the data.

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Author</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let book of books">
      <td>{{ book.id }}</td>
      <td>{{ book.name }}</td>
      <td>{{ book.author }}</td>
    </tr>
  </tbody>
</table>

Save the file and if everything is configured correctly then you can see the table with the data at this URL: http://localhost:4200/

Angular 6 Http Get Example

 

At last, Angular 6 Http Get Example Tutorial is over. You can find the source code on Github.

Github Code

Post Your Thoughts

This site uses Akismet to reduce spam. Learn how your comment data is processed.

One Response