Angular 2 Getting data from a http call

Mandy van Zetten
02-04-2018

Before reading this I suggest you know a little about Angular 2 and for the easier setup use Angular-CLI.

Service

First off before we actually start with coding, we make a service ( a place where we ask the data of a JSON file or API ).

If you use Angular-CLI just type: ng g s names in the command line it will generate your service file automatically.

So we got the service file with an empty class:

names.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class ServerService {

    constructor() { }
}

Next we of course need a place to get our data from, a JSON file or API would do just fine.

Below we make a JSON file:

names.json

{
    "data":
    [
        {
            "name":"Mandy"
        },
        {
            "name":"Lucas"
        },
        {
            "name":"Fred"
        },
        {
            "name":"Denise"
        }
    ]
}

Once we have both our service and JSON file we are ready to pass along some data!

First off we know the link to our JSON file which in this case is names.json and we add it to a variable. ( This we do to make it more clear and easy to switch to another API or JSON file if needed )

  • We add the variable inside of the class.

Of course we aren’t doing anything with this variable just yet, we need to add the HttpClient from angular to be able to get the information.
this information will transform into a Observable which hold our actual data.

  • So we import HttpClient and Observables to manage our data.

to get the data we make a simple function getNames in which we return the HTTP call with the observable which comes out of it.

names.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'; // Import HttpClient
import { Observable } from 'rxjs/Observable'; // Import Observables

@Injectable()
export class NamesService {

names = 'names.json';

getNames () {
    return this.http.get(this.names); // Use this because names is on your class their scope
}

    constructor(public http: HttpClient) { } // Don't forget to add it to your contructor so you are able to call it
}

Now our service is done we can move over to the Component that needs the data!

Component

In this Component I have used TypeScript.

  • First we Import our service so we can see the data
  • Next we add the service to the contructor so we can use the data
  • Then we make a function which we instantly call in the OnInit but can we placed anywhere when you require it
  • In this function we call the function we made in the service and subscribe to it
  • In the subscribe we make an arrow function (ES6) or normal function (ES5) and call the data we need

in this case we make a const (ES6) or var (ES5) that catches our response. So res becomes the variable response which is our JSON information.
We give this data to a this variable so it can be accessed outside of this function and in the HTML.

names.component.ts

import { Component, OnInit } from '@angular/core';
import { NamesService } from 'names.service'; // Import the service we just made

@Component({
    selector: 'app-server',
    templateUrl: './names.component.html',
    styleUrls: ['./names.component.scss']
})
export class NamesComponent implements OnInit {

names: Object;

constructor(private namesService: NamesService) { } // Add service to contructor

    updateNamesData() {
    this.serverService.getServer()
        .subscribe(res => {
            const response: any = res;
            this.server = response.data;
        });
    }

    ngOnInit(): void {
        this.updateNamesData();
    }
}

And there we go, we can use the data we got from a API/JSON file.

HAPPY CODING!

LEAVE A REPLY

you might also like